I was wondering if this is possible.
There's this element
<div id="sample_id" style="width:100px; height:100px; color:red;">
So I want to remove width:100px; and height:100px;
the result would be
<div id="sample_id" style="color:red;">
Any help would be apprreciated. :)
You can edit style with pure Javascript. No library needed, supported by all browsers except IE where you need to set to '' instead of null (see comments).
var element = document.getElementById('sample_id');
element.style.width = null;
element.style.height = null;
For more information, you can refer to HTMLElement.style documentation on MDN.
var element = document.getElementById('sample_id');
element.style.removeProperty("width");
element.style.removeProperty("height");
Use javascript
But it depends on what you are trying to do. If you just want to change the height and width, I suggest this:
{
document.getElementById('sample_id').style.height = '150px';
document.getElementById('sample_id').style.width = '150px';
}
TO totally remove it, remove the style, and then re-set the color:
getElementById('sample_id').removeAttribute("style");
document.getElementById('sample_id').style.color = 'red';
Of course, no the only question that remains is on which event you want this to happen.
Update: For a better approach, please refer to Blackus's answer in the same thread.
If you are not averse to using JavaScript and Regex, you can use the below solution to find all width and height properties in the style attribute and replace them with nothing.
//Get the value of style attribute based on element's Id
var originalStyle = document.getElementById('sample_id').getAttribute('style');
var regex = new RegExp(/(width:|height:).+?(;[\s]?|$)/g);
//Replace matches with null
var modStyle = originalStyle.replace(regex, "");
//Set the modified style value to element using it's Id
document.getElementById('sample_id').setAttribute('style', modStyle);
$("#sample_id").css({ 'width' : '', 'height' : '' });
You can simply set that style to [unset], It forces CSS to pretend that style was never assigned to the given element.
var element = document.getElementById('sample_id');
element.style.width = "unset";
element.style.height = "unset";
Specifying auto on width and height elements is the same as removing them, technically. Using vanilla Javascript:
images[i].style.height = "auto";
images[i].style.width = "auto";
Just use like this
$("#sample_id").css("width", "");
$("#sample_id").css("height", "");
Related
I created an <img/> element from js and i want it to appear only when mouseover
The callback function makesVisible() is actually called but nothing is change.
I would like to change visibility from hidden to visible
var imgHover = document.createElement('img');
imgHover.setAttribute("src", "img/icona_play.jpg");
imgHover.style.width = "30px";
imgHover.style.height = "23px";
imgHover.style.position = "absolute";
imgHover.style.margin = "0 auto";
imgHover.style.left = "45px";
imgHover.style.bottom = "35px";
//I want to change this following property
imgHover.style.visibility = "hidden";
imgContainer.appendChild(imgHover);
//Calling the function when mouseover
imgContainer.addEventListener("mouseover", makeVisible, false);
function makeVisible()
{
imgHover.style.visibility = "visible";
}
You have an option of using an opacity property instead.
Initially set it like so: imgHover.style.opacity = 0;
Than in the makeVisible method change it to imgHover.style.opacity = 1;
Another solution to this problem would be setting addEventListener method on the container div. Assuming that you can have a container around the image with exactly the same dimensions as the Image.
For example:
imgContainer.addEventListener("mouseover", makeVisible, false);
The thing is that opacity and visibility will act the same in a sense of not collapsing the space that the element should occupy. What is different though that hidden element will ignore mouse/pointer events.
Your code works as it should provided that you set up a valid reference to imgContainer and that you set a valid path to an image for the dynamically created element:
var imgContainer = document.getElementById("container");
var imgHover = document.createElement('img');
imgHover.setAttribute("src", "https://www.wpclipart.com/signs_symbol/arrows/button_arrows/play_buttons/play_button_gray.png");
imgHover.style.width = "30px";
imgHover.style.height = "23px";
imgHover.style.position = "absolute";
imgHover.style.margin = "0 auto";
imgHover.style.left = "45px";
imgHover.style.bottom = "35px";
imgHover.style.visibility = "hidden";
imgContainer.appendChild(imgHover);
imgContainer.addEventListener("mouseover", makeVisible, false);
function makeVisible(){
imgHover.style.visibility = "visible";
}
<div id="container">Hover Over Me</div>
Having said that, you should avoid setting inline styles on elements as they are hard to override when needed and they often cause duplication of code. It's much simpler to set up CSS classes ahead of time and just apply/remove those classes as needed with the element.classList API.
Also, visibility does affect whether you see an element or not, but even when you don't see it, space is allocated in the UI for it, which isn't always desirable. In most cases, using a display:none to hide an element and then simply removing that instruction to show the element is the better approach.
Lastly, while using setAttribute() is certainly valid, you can also configure your elements via their direct properties. Almost all HTML attributes map to a corresponding JavaScript object property. Using these can make the code much simpler.
Take a look at an example that puts all this together:
var imgContainer = document.getElementById("container");
var imgHover = document.createElement('img');
// Just set properties of the element directly:
imgHover.src ="https://www.wpclipart.com/signs_symbol/arrows/button_arrows/play_buttons/play_button_gray.png";
// Just add pre-made classes to style the element
imgHover.classList.add("hoverImg");
imgHover.classList.add("hidden");
imgContainer.appendChild(imgHover);
imgContainer.addEventListener("mouseover", makeVisible);
function makeVisible(){
imgHover.classList.remove("hidden");;
}
.hidden { display:none; } /* Used when an element needs to be hidden */
/* This will be applied via JS */
.hoverImg {
width:30px;
height:23px;
position: absolute;
margin:0 auto;
left:45px;
bottom:35px;
}
<div id="container">Hover Over Me</div>
Here you were appending element like this
imgContainer.appendChild(imgHover);
So reference for imgHover element in dom will get
change. Fetch that element once again inside
makeVisible() function.
document.querySelector("img") // use your appropriate.
if(typeof this.description === 'undefined') {alert('No Description Set!'); return false;}
var tempDiv = document.createElement('div'); //create a div outside of the DOM
tempDiv.className = 'descriptionColumn formBox contentRow'; //make sure and use the
//same/equivlent class(s) to ensure accuracy
tempDiv.innerHTML = this.description; //insert the text
document.body.appendChild(tempDiv); //render div
lineHeight = parseInt($(tempDiv).css('line-height')); //get the line-height (make sure this is specified in CSS!)
//also we use Jquery here to handle any vender inconsistencies,
divHeight = tempDiv.clientHeight; //get the div height
tempDiv.parentNode.removeChild(tempDiv); //clean up, delete div
delete tempDiv;
return divHeight/lineHeight; //divide the height by the line-height and return
This code works, I am trying to calculate the number of lines in a div. That said I wasn't able to get the line-height until after I added this element to the DOM.
Origionally I planned on not adding it at all because I only use it to calcuate the number of lines in the DIV.
It makes sense that it wouldn't have a height until I added it, I am just wondering if I did the right thing, or if there is a way to get the line-height without adding it to the DOM in the first place.
Rendering/Layout decision by browser is taken by browser 2 conditions:
1)new element is inserted
2)some element's style has been changed
3)sometimes when window is resized
so until the element is in DOM Tree browser will not give Layout related style to it.
consider following code:
var div = document.createElement(div);
var style = window.getComputedStyle(div);
console.log( style.color );//prints "" (empty string)
why??
because window.getComputedStyle() returns the CSS style which are actully present in DOM(browser).
now,
document.body.appendChild(div);
var style = window.getComputedStyle(div);
console.log( style.color );//prints rgb(somevalue)
why??
because rendering engine has decided the CSS properties.
//One gotcha
var div2 = document.createElement("div");
div2.style.color = "red";
console.log( $(div2).css("color") ); //prints red because jQuery gives preference to div2.style.color over window.getComputedStyle(div2);
but console.log ( window.getComputedStyle(div2).color );//prints "" .... this proves that browser has not yet decided the properties of div2
Yes, it is. But ... if you have jQuery on your page, why don't you use it?
var $div = $('<div/>', {
class: 'descriptionColumn formBox contentRow',
text: 'Description',
css: {
position: 'absolute',
left: '-99999px'
}
}).prependTo('body'); // element wouldn't be visible for user on this step
//your calculations
$div.remove();
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 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.