This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 8 years ago.
I'm uploading code from my project to Plunker. You can see it here. When I run the code through a local server and render it in Chrome, the functionality works fine. When I try to run it through Plunker the code fails.
This snippet is inside of script.js:
$('.navbar-toggle').click(function(){
alert('test1');
if ($(this).hasClass('login')) {
$('.navmenu-style1').css("z-index","1");
$('.navmenu-style').css("z-index","0");
}
else {
$('.navmenu-style1').css("z-index","0");
$('.navmenu-style').css("z-index","1");
}
});
How can I make it work in Plunker please? Is there a more universal bit of code that I can use or am I simply doing something wrong?
Cheers
You have made one of the most common mistakes anyone makes when using JQuery. You tried to attach a click handler to a DOM object before the DOM was loaded:
<html>
<head>
...
<script src="script.js"></script>
contents of script.js:
$('.navbar-toggle').click(function(){ ... });
You have to wait for the DOM to load before you run that code. Like so:
$(function () {
$('.navbar-toggle').click(function(){ ... });
});
Note: $(function) is just a shortcut for $(document).ready(function).
Related
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 2 years ago.
I am using the following jQuery code in the search bar of my website. Since I am a beginner, I am unable to relate to other code examples, hence I need help in fixing the code.
jQuery(document).ready(function ($) {
//Open Link in Search Results in New Window
jQuery('div.search_result_item_content').click(function () {
console.log("I am executed");
var menuLink = $('div.col.col-9.search_result_item_content').data('link');
window.open(menuLink, "_blank");
});
});
The code without .ready() seems to work on the console. But not on the index.js file of my website. The same file has many other jQuery functions, which are all working smoothly.
Any idea, what is causing the issue?
You are generating the items dynamically so this will not work. What you can do is what I will do below.
jQuery(document).ready(function ($) {
jQuery(document).on('click','div.search_result_item_content',function () {
console.log("I am executed");
var menuLink = $(this).data('link');
window.open(menuLink, "_blank");
});
That should work for you.
This question already has answers here:
Is it really necessary to wait for DOM ready to manipulate the DOM?
(4 answers)
Closed 4 years ago.
It seems the following inline code works by putting js right after the tag:
(1)
<div id="xx"></div>
<script>
document.getElementById('xx').addEventListener('click', aFunction);
</script>
It seems there is no need to wait document ready like this:
(2)
<div id="xx"></div>
<script>
document.addEventListener("DOMContentLoaded", function() {
document.getElementById('xx').addEventListener('click', aFunction);
});
</script>
Will the inline code (1) always work?
Please notice that I made sure <div id="xx"></div> is before the script.
You dont have to but you should. If you dont you will get errors when you try performing actions on elements in the dom when they havent been loaded yet, using document ready just ensures you dont have this issue, one less problem to debug basically.
This question already has answers here:
Why does jsfiddle throw error that function is not defined? [duplicate]
(1 answer)
Why isn't my JavaScript working in JSFiddle?
(7 answers)
Closed 6 years ago.
I'm trying to run a basic JavaScript function from an external file but I'm getting inconsistent results. Basically, I can't get a button's "onclick" event to fire when I put the script in an external JS page. I can get it work in CodePen:
CodePen
nonsense code
but NOT in JSFiddle:
JS Fiddle Examlple
I can always get it work when the script is part of the HTML page but I don't want to do that. Can you help? Thanks!
jsfiddle puts the javascript code in its own context:
//<![CDATA[
window.onload=function(){
function clickFunction()
{
alert("this is working");
}
}//]]>
But codepen puts the js in the global scope.
This question already has answers here:
window.onload vs document.onload
(9 answers)
Closed 8 years ago.
I write document.onload code inside my head tag.. but it doesn't seems to work.
here is my code..
<head>
<script>
document.onload = function () {
alert("Window Loaded...!!");
}
</script>
</head>
But if i replace with window.onload it perfectly works!!
What is the problem? Am I doing something wrong ??
As far as I'm aware, the closest you can come to your method is:
document.addEventListener('DOMContentLoaded', function () {
/* your logic here */
});
The problem you have is document may not have a method of onload for a particular browser. Luckily! The window does in most cases. :) Give that a try for your JavaScript invocation.
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 9 years ago.
first one:
function change(){
document.getElementById("clr").style.backgroundColor="red";
document.getElementById("test1").innerHTML="hwllo world";
}
second one:
document.getElementById("test1").innerHTML="hwllo world";
The first one is working fine. But the second one is not working when the file is loaded.
Javascript and HTML rendering are executed in the sequence they are found in the file. So if you're executing a piece of JS before an HTML element is rendered then the JS code wouldn't work.
This will fail:
<script>
document.getElementById("test1").innerHTML="hwllo world";
</script>
<div id="test1"></div>
This will work as expected:
<div id="test1"></div>
<script>
document.getElementById("test1").innerHTML="hwllo world";
</script>
Alternatively you can use the various onload and dom ready events to make sure that your script executes after all the HTML have been rendered:
<script>
window.onload = function(){
document.getElementById("test1").innerHTML="hwllo world";
}
</script>
<div id="test1"></div>
And what error is in console? May be you are trying to set innerHTML of not existing node? If you want to manipulate with divs, you have to do it after the page is loaded, so typically call this as body event onLoad:
<script>
function init() {
document.getElementById("test1").innerHTML="hello world";
}
</script>
<body onload="init();">
<div id="test1"></div>
...
As James Allardice said in his comment, the code is probably executed before the DOM is ready. Your code could then fail as the element might not be there. This is a known problem, but there is also a known solution. The most used solution is probably to use jQuery, which has an easy way to allow a function to only be executed after the document is ready. To use this method, first you need to include jQuery as a script reference and then modify your code as follows:
$(document).ready(function() {
document.getElementById("clr").style.backgroundColor="red";
document.getElementById("test1").innerHTML="hwllo world";
});
Now if you are using jQuery anyways, you can also rewrite your code to use jQuery selectors and make it a bit more compact:
$(document).ready(function() {
$("#clr").css("backgroundColor", "red");
$("#test1").html("hwllo world");
});
Both pieces of code are functionally equivalent.