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';
});
Related
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');
I get a Css value with JQuery ,regarding the background position of specific element,-66px -65px
I want get the second value("-65px")and change that to '170px' with jquery ;
How to subString that and replace now value?
by your case
// replace body selector with your element selector
var bgPos = $('body').css('backgroundPosition');
$('body').css('backgroundPosition', bgPos.replace('-65px', '170px'));
with jquery you can do something like this...
$('#elementid').css('background-position-x', newValueX);
$('#elementid').css('background-position-y', newValueY);
also you can get the values
$('#elementid').css('background-position-x');
$('#elementid').css('background-position-y');
I think you should try to use 'background-position' css property. It would make your life a bit simpler.
here is the fiddle
var bg = $('#some_el').css('background-position');
var values = bg.split(" ");
var X = values[0].split("px")[0];
var Y = values[1].split('px')[0]);
I've been banging my head against a wall for some time now, this is what I'm trying to do:
I have 3 div's, 2 of them have a minimum height of 300px, the 3rd columns needs to be the height of the 2 div's together + a 15px margin.
Here's a small example
http://jsfiddle.net/AAKcJ/4/
So far i've found a way to get the height of one column, but I have no idea how to calculate with it since I cant acces the variable outside of the function as I'm not really experienced with JavaScript.
var style_col1 = $("#column1").css( ["height"] );
$.each(style_col1, function( prop, value ) {
var height_col_1 = value;
});
var style_col2 = $("#column2").css( ["height"] );
$.each(style_col2, function( prop, value ) {
var height_col_2 = value;
});
Any help is appreciated :)
You can take a global variable which is visible in both functions
var height = 0;
$('#column1,#column2').each(function(){
height += $(this).height();
});
$('#column3').css('height', height+15);
or
height = $('#column1')height()+$('#column2')height();
$('#column3').css('height', height+15);
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).
How do you find the current width of a <div> in a cross-browser compatible way without using a library like jQuery?
document.getElementById("mydiv").offsetWidth
element.offsetWidth (MDC)
You can use clientWidth or offsetWidth Mozilla developer network reference
It would be like:
document.getElementById("yourDiv").clientWidth; // returns number, like 728
or with borders width :
document.getElementById("yourDiv").offsetWidth; // 728 + borders width
All Answers are right, but i still want to give some other alternatives that may work.
If you are looking for the assigned width (ignoring padding, margin and so on) you could use.
getComputedStyle(element).width; //returns value in px like "727.7px"
getComputedStyle allows you to access all styles of that elements. For example: padding, paddingLeft, margin, border-top-left-radius and so on.
Another option is to use the getBoundingClientRect function. Please note that getBoundingClientRect will return an empty rect if the element's display is 'none'.
var elem = document.getElementById("myDiv");
if(elem) {
var rect = elem.getBoundingClientRect();
console.log(rect.width);
}
You can also search the DOM using ClassName. For example:
document.getElementsByClassName("myDiv")
This will return an array. If there is one particular property you are interested in. For example:
var divWidth = document.getElementsByClassName("myDiv")[0].clientWidth;
divWidth will now be equal to the the width of the first element in your div array.
Actually, you don't have to use document.getElementById("mydiv") .
You can simply use the id of the div, like:
var w = mydiv.clientWidth;
or
var w = mydiv.offsetWidth;
etc.
call below method on div or body tag onclick="show(event);"
function show(event) {
var x = event.clientX;
var y = event.clientY;
var ele = document.getElementById("tt");
var width = ele.offsetWidth;
var height = ele.offsetHeight;
var half=(width/2);
if(x>half)
{
// alert('right click');
gallery.next();
}
else
{
// alert('left click');
gallery.prev();
}
}
The correct way of getting computed style is waiting till page is rendered. It can be done in the following manner. Pay attention to timeout on getting auto values.
function getStyleInfo() {
setTimeout(function() {
const style = window.getComputedStyle(document.getElementById('__root__'));
if (style.height == 'auto') {
getStyleInfo();
}
// IF we got here we can do actual business logic staff
console.log(style.height, style.width);
}, 100);
};
window.onload=function() { getStyleInfo(); };
If you use just
window.onload=function() {
var computedStyle = window.getComputedStyle(document.getElementById('__root__'));
}
you can get auto values for width and height because browsers does not render till full load is performed.