jQuery .css("margin-left") - javascript

I made a kind of game in javascript and in this game there are some divs which are horizontally moving with different transition times. In this game there is a function which is called each 1/100 seconds. Then it first checks it position with:
$("class1").css("margin-left")
And now the weird thing: when I set the class in html like:
<div class = "class1"></div>
The .css("margin-left") works perfectly, but when I don't set a class in html and I add the class in js like:
$("div:nth-child(6)").addClass("class1");
Then the $(theclass).css("margin-left") give wrong outputs.
I tried with the .position and .offset but those both didn't work for me.
My code:
function newBlock(block, marginTop, bgc, height, hoogte1, hoogte2, v, tijd){
block.css("background-color", bgc).css("height", height).css("margin-top", marginTop);
var movement1 = "movement1";
var movement2 = "movement2";
// if (positionPixelsBlockF > 0){
// positionPixelsBlockF = positionBlockF.slice(0, 3);
// }
setInterval(positie, 10);
function positie(){
tijd = tijd + 1;
if (v != 0){
block.addClass("i" + v);
$(".i" + v).css({"width": "50px", "display": "inline-block", "position": "absolute", "z-index": "20"});
var positionBlockF = $(".i" + v).css("margin-left");
var positionPixelsBlockF = positionBlockF.slice(0, 4);
$("#uitleg4").html(positionPixelsBlockF);
else if (v === 0){
var positionBlockF = $(".b1").css("margin-left");
var positionPixelsBlockF = positionBlockF.slice(0, 4);
Don't mind the incomplete use of the {}, but in my code that's fixed.
PS: using brackets

I believe you are missing a dot before class1 selection, in jquery there are two types of elements selection either by class like $(".ElemnetClass") OR by ID like $("#ElementID")
More info about .css()

This Is An Example Of Your Requirement
$(".class").css('margin-left','10px');// Some Px (or) percentage Your Based On Requirement
You Can Use This Type Also Firstly You Create One Class Of Your Requirements
And Use Below Code
$("#ElementId").addClass('created classname Here');

Related

How Can I set variable width with !importanat using JavaScript/jQuery

Ia have a div named "#idDayNrCell". I want to get its width then do some calculations and apply it to another div called ".event". I am using bootstrap so i need to apply !important aswell. I am new to javascript/jquery.
I tried something like this. But it didn't wotk
$(document).ready(function(){
var cellWDTstr = ($("#idDayNrCell").css("width")); //get width
var cellWDT = cellWDTstr.substr(0,cellWDTstr.length-2); //remove the "px" part
console.log(cellWDT);
var GunSayisi=2; //how long is the event (2 for example)
// after tihs things get complicated for me
// if the even is minimum 2 days i need a different width. calculated below
var wdtEnAz2 = ((cellWDT-30)*GunSayisi + 30*(GunSayisi-1)).toString();
console.log(wdtEnAz2);
var setWdt = GunSayisi>1 ? wdtEnAz2 : calWdt;
//after here it is expoerimental code which I am failed
console.log(setWdt);
setWdt+= 'px';
console.log(setWdt);
$(".event").style.setPsetProperty('width',setWdt,'important');
});
this is the html
Using ES6,
var width = "100px";
$(".event").attr('style', `width: ${width} !important`);
Add like this :
$('.event').attr('style', 'width: '+ setWdt +' !important');
You can use css property from jquery, please find below code snippet :
$(".event").css( "width", function(
setWtd ) {
return setWtd + '!Important';
});

CSS/JS - Can you treat browser auto line breaks like rows to color them?

I am not quite sure how to put my Question in the right words, but I try to describe what I want to do.
Let's say we have a set of data (eg. numbers) from a database and they need to be output as a list. I put a predefined amount of data-fields in a row (for dekstop systems). Every data is in a SPAN with color/margin/padding styles. (Like table-cells.) After that amount of Spans is reached, a forced line break is given. And with each line break, the background color for all spans in that "row" is altered (odd/even). So far no problem.
However, if now someone checks that page with a Smartphone (or you simple resize your Browser Window), the predefined amount does not fit anmyore. As example, in large resolutions you have 6 Spans side by side, colored odd, than 6 Spans colored even. In a small resolution you maybe only have 3 Spans side by side, however in my design you have still 6 Spans colored odd, so two "rows" with the same background-color before it is altered.
Example HTML Output:
<span class="odd">Number 01</span>
<span class="odd">Number 02</span>
<span class="odd">Number 03</span>
<span class="odd">Number 04</span>
<span class="odd">Number 05</span>
<span class="odd">Number 06</span>
<br/>
<span class="even">Number 07</span>
<span class="even">Number 08</span>
<span class="even">Number 09</span>
<span class="even">Number 10</span>
<span class="even">Number 11</span>
<span class="even">Number 12</span>
<br/>
I have absolutely no idea if it is possile to get to know - maybe through Javascript or CSS, how many spans are displayed in a "row", to automate the odd-even-coloring, make it in a way responsive.
Check my Fiddle to maybe show better what I'm trying to get.
Don't you want to use any css framework? Like Bootstrap or Foundation? I hope that will make your work more easier.
Please go through the link.
https://getbootstrap.com/examples/grid/
It already has the solution for mobile device and medium screen.
I can't think of any way to pull it off with CSS, but here's a javascript solution. Browser support is a little off. Didn't realize you tagged jQuery in your post, but it should work on modern browsers at least:
window.addEventListener('resize', function(){
var cells = document.querySelectorAll('.odd,.even');
var activeClass='even', activeLine = 0;
for(var i = 0, len = cells.length; i < len; i++) {
cells[i].classList.remove('odd');
cells[i].classList.remove('even');
if(activeLine != cells[i].offsetTop + cells[i].offsetHeight) {
activeClass = (activeClass === 'even') ? 'odd' : 'even';
activeLine = cells[i].offsetTop + cells[i].offsetHeight
}
cells[i].classList.add(activeClass);
}
});
/* edit: forgot to dispatch the event.
jQuery makes this so much easier to write
than the monstrosity below. */
var event;
event = document.createEvent("HTMLEvents");
event.initEvent("resize", true, true);
window.dispatchEvent(event);
Demo here: http://jsfiddle.net/xh0o6gvy/1
Edit: Here is the jQuery version that Sunny put together found in a fiddle from the comment below. It's definitely a better way to go than the above code if compatibility with older browser versions is required.
function colorSpans() {
var containers = $('.span_container');
containers.each(function() {
var activeClass = 'even';
var activeLine = 0;
var cells = $(this).children('.odd, .even');
cells.each(function() {
$(this).removeClass('odd even');
var offset = $(this).offset();
var height = $(this).outerHeight();
if(activeLine != offset.top + height) {
activeClass = (activeClass === 'even') ? 'odd' : 'even';
activeLine = offset.top + height;
}
$(this).addClass(activeClass);
});
});
}
$(window).on('resize', function() {
colorSpans();
});
colorSpans();
Thanks everybody for your help and inspirations!
So just to round it up, here is the final function I am now using that works with fixed and variable container sizes and recolors container by container.
function colorSpans() {
var containers = $('.span_container');
containers.each(function() {
var activeClass = 'even';
var activeLine = 0;
var cells = $(this).children('.odd, .even');
cells.each(function() {
$(this).removeClass('odd even');
var offset = $(this).offset();
var height = $(this).outerHeight();
if(activeLine != offset.top + height) {
activeClass = (activeClass === 'even') ? 'odd' : 'even';
activeLine = offset.top + height;
}
$(this).addClass(activeClass);
});
});
}
An here is the fiddle: http://jsfiddle.net/z9db7p0t/1/
You could accomplish this with Javascript or plain CSS depending on the rest of your HTML/CSS.
Are the width of the span elements fixed? What about their parent container? If so, you should know where the breakpoints in your layout exist and easily target the elements via css within the proper media queries.
If the size is dynamic, you could update the classes on the spans by calculating how many spans could fit in a row. This would need to be called each time the page was resized however. Using jQuery:
$(function() {
var container = $('#span-container'),
spans = container.find('span');
$(window).on('resize', function(evt) {
var containerWidth = container.width(),
spanWidth = spans.width();
var howManyPerRow = Math.floor(containerWidth / spanWidth);
//reset rows
spans.removeClass('odd even');
var row = 'odd',
c = 1;
spans.each(function() {
$(this).addClass( row );
if( c % howManyPerRow == 0 ) {
row = (row == 'odd') ? 'even' : 'odd';
}
c++;
});
});
});
You are going to need to remove the <br /> tags for this to work correctly. Also, you should set white-space: nowrap; on the spans IMO.

How to use jQuery event in sequence

I am trying to play around with learning jQuery and have made the following jsFiddle:
http://jsfiddle.net/jkNK3/
The idea is to have a div's color change on click. Fine, I got that but I am wondering if there is a way to have the div's color change through multiple classes changes, perhaps with some sort of array or loop. Let me explain.
I have created several CSS classes like so:
.color1 {..}
.color2 {..}
.color3 {..}
.color4 {..}
.color5 {..}
.color6 {..}
and am wondering if we can do something like
addClass("color" + i)
where i can be looped through 1 - 6.
Is there any way to accomplish this? Thanks for the help.
This is a good place to consider the danger of global javascript namespaces. Here's a simple example that takes advantage of closures to avoid that with jquery:
$(function() {
var numb = 1;
// this bit of managing the color state swap is another topic for discussion, so keeping it simple
var colors_len = 6;
$("div").click(function() {
// this closure has access to the numb variable
if (numb < colors_len) {
numb++;
$(this).addClass("color" + numb);
$(this).removeClass("color" + (numb-1));
} else {
numb = 1;
$(this).removeClass("color" + colors_len);
$(this).addClass("color" + numb);
}
});
});
http://jsfiddle.net/2taH5/
ps. Jquery ui also has a swap class method but that is more for animations
In my opinion the easiest would be to just store the color number in jQuery's handy data(), and then increment it from that:
function fnClick() {
var numb = $(this).data('color') || 2;
$(this).addClass("color" + numb).data('color', ++numb)
}
FIDDLE
To make it go back to the first color after the last color etc
function fnClick() {
var numb = $(this).data('color') || 2;
numb = numb == 7 ? 1 : numb;
$(this).removeClass().addClass("color" + numb).data('color', ++numb)
}
FIDDLE
How about using a random number to give a random color to the div.
var classCount = 6;
$(document).ready(function () {
$("div").on("click", fnClick);
});
function fnClick(e) {
// Get the currently clicked element
var $this = $(e.target),
className = 'color' + Math.floor((Math.random() * classCount )+1);
// Remove the exixting class/s
$this.removeClass();
// Add the class
$this.addClass(className);
}
Check Fiddle

How to get margin value of a div in plain JavaScript?

I can get height in jQuery with
$(item).outerHeight(true);
but how do I with JS?
I can get the height of the li with
document.getElementById(item).offsetHeight
but i will always get "" when I try margin-top:
document.getElementById(item).style.marginTop
The properties on the style object are only the styles applied directly to the element (e.g., via a style attribute or in code). So .style.marginTop will only have something in it if you have something specifically assigned to that element (not assigned via a style sheet, etc.).
To get the current calculated style of the object, you use either the currentStyle property (Microsoft) or the getComputedStyle function (pretty much everyone else).
Example:
var p = document.getElementById("target");
var style = p.currentStyle || window.getComputedStyle(p);
display("Current marginTop: " + style.marginTop);
Fair warning: What you get back may not be in pixels. For instance, if I run the above on a p element in IE9, I get back "1em".
Live Copy | Source
Also, you can create your own outerHeight for HTML elements. I don't know if it works in IE, but it works in Chrome. Perhaps, you can enhance the code below using currentStyle, suggested in the answer above.
Object.defineProperty(Element.prototype, 'outerHeight', {
'get': function(){
var height = this.clientHeight;
var computedStyle = window.getComputedStyle(this);
height += parseInt(computedStyle.marginTop, 10);
height += parseInt(computedStyle.marginBottom, 10);
height += parseInt(computedStyle.borderTopWidth, 10);
height += parseInt(computedStyle.borderBottomWidth, 10);
return height;
}
});
This piece of code allow you to do something like this:
document.getElementById('foo').outerHeight
According to caniuse.com, getComputedStyle is supported by main browsers (IE, Chrome, Firefox).
I found something very useful on this site when I was searching for an answer on this question. You can check it out at http://www.codingforums.com/javascript-programming/230503-how-get-margin-left-value.html. The part that helped me was the following:
/***
* get live runtime value of an element's css style
* http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element
* note: "styleName" is in CSS form (i.e. 'font-size', not 'fontSize').
***/
var getStyle = function(e, styleName) {
var styleValue = "";
if (document.defaultView && document.defaultView.getComputedStyle) {
styleValue = document.defaultView.getComputedStyle(e, "").getPropertyValue(styleName);
} else if (e.currentStyle) {
styleName = styleName.replace(/\-(\w)/g, function(strMatch, p1) {
return p1.toUpperCase();
});
styleValue = e.currentStyle[styleName];
}
return styleValue;
}
////////////////////////////////////
var e = document.getElementById('yourElement');
var marLeft = getStyle(e, 'margin-left');
console.log(marLeft); // 10px
#yourElement {
margin-left: 10px;
}
<div id="yourElement"></div>
Here is my solution:
Step 1: Select the element
Step 2: Use getComputedStyle and provide the element to it
Step 3: Now access all the properties
const item = document.getElementbyId('your-element-id');
const style= getComputedStyle(item);
const itemTopmargin = style.marginTop;
console.log(itemTopmargin)
It will give you margin with px units like "16px" which you might not want.
You can extract the value using parseInt()
const marginTopNumber = parseInt(itemTopmargin)
console.log(marginTopNumber)
It will give you the numerical value only (without any units).

Dynamically changing costs in custom pc builder with checked inputs

First, please take a look at my fiddle.
I'm trying to figure out a clean way of making the price next to each item change when any item is selected (in that group, you can image that there will be graphics cards etc in a different section which also will need the same functionality).
If its positive I need the class to be .positive and vice versa, and if the item is selected (+0) then the price difference wont be displayed.
This will also be used on checkbox's.
Non-working example.
You'll want to compare each selected item with items having the same name. In the .each() loop in CalculatePrice(), pass the checked item to this function:
function CalculateDiffs(item) {
var selectedPrice = +item.data("price");
item.siblings(".item_price").text("");
$(".calculation-item[name='"+item.attr("name")+"']").not(item).each(function(){
var price = +$(this).data("price");
var diff = (price-selectedPrice).toFixed(2);
if (diff >= 0) {
diff = "+"+diff;
}
$(this).siblings(".item_price").toggleClass("negative", diff < 0).text(diff);
});
}
As for checkboxes, the above function will take care of hiding the price when it is checked. To display the prices for unchecked checkboxes:
$(".calculation-item:checkbox:not(:checked)").each(function(){
$(this).siblings(".item_price").text("+"+$(this).data("price"));
});
Or, if you want to display the price of a checked checkbox as negative, use this instead:
$(".calculation-item:checkbox").each(function(){
var diff = (this.checked ? "-" : "+") + $(this).data("price");
$(this).siblings(".item_price").toggleClass("negative",this.checked).text(diff);
});
http://jsfiddle.net/gilly3/HpEJf/8/
Actually it's pretty straight forward, all you'll need to do is calculate the difference between the selected price and the price of all the options in the list. Eg, something like this:
$(".calculation-item").each(function(index) {
var my_cost = base_price + $(this).data("price");
var difference = Math.round(my_cost - base_cost);
});
I've created a working jsFiddle for you here: http://jsfiddle.net/HpEJf/6/. You'll need to implement decimal rounding etc but this should put you on the right track :)
If my understanding is correct, you want to display the cost difference from the previously selected radio button and the currently selected radio button.
To do that you need to keep track of the previously selected button. The only way I know of to do that is to set a variable outside the clickhandler scope to keep track of it and update the element in the clickhandler.
The rest is fairly straightforward. I updated your jsFiddle with an example of how to do it. The relevant code is below:
Adding at top of script:
//global for last checked/selected radio
var lastSelection = $(".calculation-item:checked");
//clear existing price diffs set by markup
$('span.processor_price').text('');
Added another function:
function priceDifference(oldPrice, newPrice) {
var difference = {
'cssClass': '',
'inCost': '0'
};
var fixedDiff = '';
var diff = newPrice - oldPrice;
diff = Math.ceil(Math.abs(diff * 100)) / 100;
fixedDiff = diff.toString();
if (newPrice < oldPrice) {
difference.cssClass = 'negative';
difference.inCost = '-' + fixedDiff;
} else if (newPrice > oldPrice) {
difference.cssClass = 'positive';
difference.inCost = '+' + fixedDiff;
}
/* else {
* must be the same, no reason for this block
* as the default empty string will suffice
* as will the cost difference of 0
}*/
return difference;
}
And changed your click handler to:
$(".calculation-item").click(function() {
var difference = {};
if (lastSelection) {
//get difference
difference = priceDifference($(lastSelection).data("price"), $(this).data("price"));
//change class
$(this).siblings('span.processor_price').addClass(difference.cssClass).text(difference.inCost);
$(lastSelection).siblings('span.processor_price').removeClass('positive').removeClass('negative').text('');
if (lastSelection !== this) {
lastSelection = this;
}
} else {
lastSelection = this;
}
CalculatePrice();
});​

Categories