Code won't execute in $(document).ready but will in developer console - javascript

I have some code wrapped in $(document).ready(function(){ /*code*/ });, and all of it works fine, except for one line. The code above it works fine, the code below it works fine, I'm not getting any errors in my console.
$('.main-right.category').height( $('.footer').height() + $('.main-right.category').height() );
That doesn't fire. However, if I paste that exactly in the developer console and press enter after the page has loaded, it works. All of the elements exist at page load (meaning none are built dynamically via javascript). Same result in chrome, firefox, IE.
Any ideas?
edit: I should add that my css is loaded before my javascript, and I've done other CSS related tweaks in this same javascript file that have worked fine.
Also, if I console.log $('.main-right.category').height() and $('.footer').height() right above that line of code, they both give non-zero integer values like I'd expect.

The ready event fires when the DOM is ready to work with. It differs from the load event which fires when all assets (css, javascript, images, ...) are all loaded.
I guess that when you code runs, the elements you're trying to get the height does have an height calculated already so it seems nothing happens.
When you executed your code in the console, everything is loaded so the behavior is the one expected.
To bind to the load event, check the method .load().

$(document).ready fires when the DOM-structure is full available, at this time the rendering ususally isn't finished, so the dimensions of the elements may be unknown and height() will return wrong values.
Use $(window).load() instead.

i usually set height with:
var height = $('.footer').height() + $('.main-right.category').height();
$('.main-right.category').css('height',height+'px');

You should use the console to debug the selectors and view the heights of the elements;
$(document).ready(function() {
var $footer = $('.footer');
var $category = ('.main-right.category');
console.log($category, $footer);
console.log($category.height(), $footer.height());
console.log('New height =', ($category.height() + $footer.height()));
});

Related

Script that works in the browser console but not when in the code

I have a very simple piece of javascript code that just should work and it only works when I run it in the browser console:
<script>
$(".hopscotch-close").click(function () {
alert("Hi");
Cookies.set("tourState", "closed")
})
</script>
Because it runs in the console I know that:
1) the ".hopscotch-close" is OK;
2) there are no errors in the code that could prevent it from running;
Also:
1) because is a "click" event I know that I haven't got a problem with the DOM being ready (and I can put everywhere - but in this case in at the bottom of the <body>;
2) I know I don't have an issue because of using the same name for a class than something else that exist;
3) The behavior is the same in Safari and Firefox, so its not a Browser issue.
I know this is tough without the full code, but if someone has experienced this maybe has na idea about what could be the problem.
From your comments I sense that the element is getting appended dynamically so instead of
$(".hopscotch-close").on('click',
you need to make use of event-delegation as
$(document).on('click','.hopscotch-close',function(){
That will do the trick.
If you are appending .hopscotch-close to any already existing static
element then instead of $(document).on('click' you can use
$('#yourStaticElementId').on('click','.hopscotch-close',function(){
which improves site performance.

childNodes list is empty before page is loaded

// Some jQuery to load the HTML file
$(function(){
$("#myDiv").load("./someHTMLfile.html");
});
var div = document.getElementById("myDiv");
console.log(div.childNodes);
console.log(div.childNodes[0]); // Prints undefined
When this code runs, the list div.childNodes is empty, but when I check the variable in the Chrome console, the list is not empty. Chrome also tells me that "Object state below is captured on first expansion".
When I execute console.log(div.childNodes[0]) in the Chrome console, it returns the first element, as it should. I've also tried to make the script execute after the page is fully loaded with jQuery $(document).ready(), but it didn't solve anything.
Why is this and how do I fix it?
load runs asynchronously, plus you've wrapped it in the jQuery ready function. All this means that console.log(div.childNodes) is running well before someHTMLfile.html has been loaded and inserted.
What you need to do is use the callback function available in load to run any functionality that depends on the html:
$(function(){
$("#myDiv").load("./someHTMLfile.html", function() {
var div = document.getElementById("myDiv");
console.log(div.childNodes);
console.log(div.childNodes[0]);
});
});

JQuery's $("*", document) returns only one item: html

I have a page with two frames on it, and I have managed to respond to reloads of one of these frames. In the handler for the reload, I am trying to select an item on the newly loaded frame using jQuery, like so:
$("frame[name=WorkArea]").on("load", function () {
console.log("Reloaded work area."); //this works fine
alert($("tr.hdr", "frame[name=WorkArea]").html());
});
The alert box says "undefined." When I experiment at console to 'select everything',
$("*", "frame[Name=WorkArea]")
only one item is listed: the raw html of the frame.
So basically I can't select anything within the frame. It looks like the DOM is not yet constructed for the HTML contents of the frame (?) What am I missing?
PS Not sure this is relevant, but it's within an injected content script for a Chrome extension.
Try this,
$("frame[name=WorkArea]").on("load", function () {
console.log("Reloaded work area."); //this works fine
alert($(this).contents().find('tr.hdr').html()); // use this and find() here
});
Try with .find() in jquery
$("*").find("frame[name=WorkArea]").html();
or
$(document).find("frame[name=WorkArea]").html();

Prevent inline scripts loading until Jquery has been loaded

Ok, I have a Jquery script, its function is to determine the width of the window, onload. If the width is greater than 642px it calls .load() to load an image slider. The reason for this is mobile devices will neither be served the images or js required for the slider.
This worked fine when jquery was loaded in the head. Upon moving to the footer its breaking. The code is included from the index.php. Could this be whats causing it? I would have thought once php built the page jquery parsed the content?
It appears the code is parsed before the jquery is loaded. Can anyone suggest a way to get round this please?
I have thought of creating the code as pure JS or using a delayed load, but I cant seem to figure out how to get it working.
There must be much better solutions? I feel like I’m missing something very obvious..
contents of the included script:
<script type="text/javascript">
$(window).bind("load", function() {
// code here
$(window).width(); // returns width of browser viewport
var width = $(window).width();
if (width >= 642) {
$('.slider-content').load("templates/include/slider.php", function () {
$('.slider-content').show(200);
});
}
else {
//alert('small')
}
});
</script>
Thanks,
Adam
In some environments, you must use jQuery() instead of $(). See this question.
Other than that, your problem might have to do with the document not being complete yet or binding to an event that has already passed. Try this instead:
jQuery(document).ready( function($) {
// Your code goes here. (You can safely use the $() function inside here.)
});

Javascript get height IE wrong values

I have strange problem in my application that I can't solve. In my code I do something like this:
$tds.each(function(index) {
parentHeightArray.push($(this).parent().outerHeight());
});
$tds is simply a jquery object containing all <div> tags that are in table cell.
In FF it returns correct values, but in IE they are too low. When I execute the same code in setTimeout function I get good values what can cause this behaviour?
It may have something to with either the DOM not fully constructed or the content not fully loaded.
Try putting your JavaScript inside of:
$(document).ready(function() {
// your code
});
or inside of:
$(window).load(function () {
// your code
});
Also make sure that you have a doctype that doesn't trigger the quirks mode. See: Triggering different rendering modes on Wikipedia.

Categories

Resources