I need to get the width of a newly added item using JavaScript or jQuery. I know if I need to bind an event to a newly added element I can use event delegation or the .on() method in jQuery. But in this case I’m not binding an event I just need to get the width of that element. How can I do that?
$('#box').width(); // won’t work
document.getElementById("box").width; // won't work either
To get the width
You can just use jQuery's .width() method:
$('#box').width() // Should give you the pixel width with no px/rem/%
// Or plain ol' Vanilla JS
document.getElementById('box').offsetWidth
// Or mix it up
$('#box')[0].offsetWidth
Possible issues
Make sure your element has been created, it is visible and you added it to the DOM.
Your element contains floated elements or absolutely positioned elements and therefore has not gained any width.
You're trying to retrieve the elements width prior to the DOM rendering.
Make sure your element is not affected by any stylesheet and has somehow become inline.
Loading issue
Make sure that your script is on the bottom of the page and/or you are using jQuery's .ready() method:
$(document).ready(function(){
$('#box').width();
});
// Shorthand for the above
$(function(){
$('#box').width();
});
Demos
VanillaJS Demo
jQuery Demo
If anyone can think of other issues or solutions please contribute to the answer.
Try this:
var box = document.getElementById('box');
alert(window.getComputedStyle(box).width);
Related
I am trying to calculate the minimum height an iframe needs to be fully displayed.
To realise this, I tried the following approach:
var neededSize = $(window.document).height();
// Get the jquery of the parent in order to resize the frame
var par = window.parent;
if(par != null) {
var jq = par.jQuery;
var frameParent = jq('#' + window.frameElement.id);
frameParent.height(neededSize);
}
The problem with this approach is that the iframe contains some hidden elements (display: none;). When I use jQuery.height() it returns the minimum height it needs including the hidden elements.
Does anyone know an approach through jquery or standard javascript to get the minimum height excluding the height the hidden divs take or should i calculate this myself? (get all the hidden fields and substract each height?)
Try wrapping it in the document ready handler shorthand:
$(function(){
//your code here
});
Documentation:
The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.
So the code will be executed after all DOM elements are rendered. And probably the height is consistent then with the hidden elements. (they are probably shown in a split second because the .css is still loading)
I am new to jQuery and such kind of js frameworks. Till now I used to do like this
<div onclick="function()"></div>
But in jQuery we get the element and add the event there. How can I detect all events added on a div?
I have a div whose height is set to the remaining height. Then I cant find appropriate css for that. I strongly believe that it has been done from javascript. I cant find relavant code any where. I dont know how to debug this.
Any help is highly appreciated.
To answer your question you can use:
jQuery._data( elem, "events" );
This will become an object of all events attached to the selected element.
This will return undefined when no event is attached to the element.
Note that this should be a single element, so for a class you should use:
$._data($('.class')[0], "events")
Which only select the first element with that class, instead of all the elements with that class.
jsFiddle
Source: jQuery find events handlers registered with an object
For each checkbox on the web page, I replace it with a slider that I borrowed from jsfiddle.net/gnQUe/170/
This is done by going through the elements when the document is loaded.
Now the problem is that when more content is loaded via ajax, the new checkboxes are not transformed.
To solve the problem, I used AjaxComplete event to go through all the elements again and replace the checkboxes with sliders.
Now the problem happens that elements that were already replaced, get two sliders. To avoid that I check if the checkbox is hidden and next element is div of class "slider-frame", then don't process the re-process the element.
But I have a lot of other such controls as well, and I am presume I am not the only one that has this problem. Is there another easy way around it?
There exists jQuery live/on( http://api.jquery.com/on/ ) event but it requires an event as an argument? whereas I would like to change the look of my controls when they are rendered.
Another example of the same problem is to extend some controls that are loaded via ajax with jQuerys autocomplete plugin.
Is there a better way to accomplish this other than changing some attributes on the element.
To summarize, on document load I would like to process every element in DOM, but when more elements are loaded via ajax then I want to change only the new elements.
I would assume that when the element's are transformed into a slider, a class is added to them. So just add a not clause.
$(".MySelector").not(".SomeClassThatSliderAddsToElement").slider({});
So in the case of your code do something like this
$('.slider-button').not(".sliderloaded").addClass("sliderloaded").toggle(function(){
$(this).addClass('on').html('YES');
$('#slider').val(true);
},function(){
$(this).removeClass('on').html('NO');
$('#slider').val(false);
});
Since you said you do not want to add anything else, how about you change the toggle function to click.
$(document).on("click", ".slider-button", function(){
var elem = $(this);
elem.toggleClass("on");
var state = elem.hasClass("on");
elem.text(state?"YES":"NO");
elem.parent().next().val(state);
});
Running fiddle: http://jsfiddle.net/d9uFs/
I'm trying to dynamically change the css properties of a jquery masonry plugin box.
Essentially, I'm going to make the box expand, i've this code, but it yields no results.
$container.click(function(){
var elem = document.getElementById($container);
elem.style.width="500px";
});
I expect for the width of the block to change to 500px when I click on it, but it doesn't.
Any insight on dynamically changing css via javascript would be great. Thanks!
All you need is:
$(this).css('width', '500px');
in the "click" handler. (That's assuming that the "container" is the box whose size you want to change.)
Change the handler internals to
$container.css({width:"500px"});
I have some html that is generated programmatically using javascript at runtime.
I want to be able to dynamically change the css properties of this html
e.g.
$(".pointsbox").css("background-color","green");
but it appears to not work as those html elements are not available at the time that the css change is called.
I am pretty sure I have managed to do this before but I've forgotten what the function is called.
Any help much appreciated!
You haven't posted code on how exactly you create your HTML elements, but it can be something as simple as this:
You can create an HTML element by passing HTML into the jQuery function right?
var new_element = $('<div>');
Well, you can treat that like any other jQuery object, and just manipulate its CSS right then and there.
var new_element = $('<div>').css('background-color', 'green');
Heck, you can even chain the create, the css change and the DOM insert in one call.
var new_element = $('<div>')
.css('background-color', 'green')
.appendTo('#container')
;
There are the Mutation events - specifically the DOMNodeInserted event - that you could bind an event handler to. However, as the page I linked states, it's recommended that you don't because it has a serious negative effect on the performance of your page and the cross-browser support isn't particularly good.
An alternative is to simulate your own DOMNodeInserted event using a custom event. Essentially you bind a handler for a custom event (say nodeinserted) on the document, then trigger that event whenever you have code that dynamically modifies the structure of your page. Code might look something like the following:
$(document).on('nodeinserted', function() {
$('.pointsbox').css('background-color', 'green');
});
function modifyPage() {
// code to modify your page here
$(document).trigger('nodeinserted');
}
Note that, with this approach, you'll need to modify all functions that add elements to the page to trigger that nodeinserted custom event.
I use this. It ensures the DOM has loaded.
$(document).ready(function(){
//code here
$(".pointsbox").css("background-color","green");
});