I am trying to grab an element (a button) and add an event listener on it.
Whenever I run
var button = document.getElementById('clickMe');
console.log(button); // null
I checked that my javascript file is loading and checked that everything is case sensitive. Here is my html and JS Files:
HTML:
<!doctype html>
<html>
<head>
<script src="js/timer.js"></script>
</head>
<body>
<button id='clickMe' type='button'>Hello</button>
</body>
</html>
JS
var button = document.getElementById('clickMe');
console.log(button);
function buttonClicked () {
alert('the button was clicked');
}
button.addEventListener('click', buttonClicked);
function timerComplete () {
alert('timer complete');
}
setTimeout(timerComplete, 2000);
The most common errors I have found was camel casing getelementbyid which I did.
Does anyone know why I keep getting null? Is it trying to grab the element before it is loaded?
Your Javascript code is executed before the Button is added to the DOM. You could change your HTML to this:
<!doctype html>
<html>
<body>
<button id='clickMe' type='button'>Hello</button>
<script src="js/timer.js"></script>
</body>
</html>
Or even better, if you don't mind making your JS code a bit more complex you could wait for your dom elements to be loaded before executing that part of the code:
document.addEventListener('DOMContentLoaded', function() {
var button = document.getElementById('clickMe');
console.log(button);
});
If you use this JS you can put back your script tag back to the head
Related
I have a header which I use in several pages, so I would like to use jquery to import it into each page so that I don't have to make any changes several times, using this code:
$(document).ready(function() {
$('#header').load("header.html");
});
The header loads fine, but the problem is that I have a button within that header which I have assigned to a variable:
var headerButton = document.querySelector('.header__header-button')
And I have added an event listener to this button in order to execute some code when it's pressed:
headerButton.addEventListener('click', function () {
The problem is that I'm getting an error in the javascript console:
TypeError: headerButton is null page.js:17:1
The problem seems to be that the variable is being assigned the value before the Html has loaded, although I am not sure.
There is nothing wrong with the variable or the EventListener, it all works when the header is within the main file. So, what can I do to solve this?
.. Or, maybe there is a better way to import Html that I am unaware of?
You should use $(document).ready() inside of header.html as well to make sure your DOM is available before you try to manipulate elements with JavaScript.
Here's an example of the page you're trying to load header.html into:
<!-- index.html -->
<html lang="en">
<head><!-- ... --></head>
<body>
<div id="header"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#header").load("header.html");
});
</script>
</body>
</html>
Then, inside of your header.html, do the following:
<!-- header.html -->
<header>
<p>This is a header.</p>
<button id="button" type="button" className="header">
Header button - click me!
</button>
</header>
<script>
$(document).ready(function() {
var btn = document.getElementById("button");
btn.addEventListener("click", function() {
alert("button was clicked");
});
});
</script>
Here's a working example if you'd like to see a demo:
CodeSandbox
You can try using the callback function.
$(document).ready(function() {
$('#header').load("header.html", () => {
var headerButton = document.querySelector('.header__header-button');
headerButton.addEventListener('click', function () {});
});
});
I was trying to execute a function using .click (jquery 3.4.1) when a button is pressed but the function executes as soon as the page loads. And after some trying I thought there might be some piece of code that is making it behave this way so I created new files with basic elements and tried using it but it still didn't work. I thought I might be doing something wrong and so I checked a tutorial but it didn't help because I was doing the same thing.
I tried .on('click', function) too but the result was same.
The .html file
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1 style="text-align: center;">Some Text</h1>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="test.js"></script>
</body>
</html>
The .js file
$('h1').click(console.log('Clicked'))
Any idea why it isn't working?
You are attaching a click event listener to the h1
$('h1').click(console.log('Clicked'))
What is does is it executes the console and what it returns is assigned to the event listener. So that is why it is not working. You basically just did the following because console does not return anything.
$('h1').click(undefined)
so you have to assign it a function
$('h1').click(function () { console.log('Clicked') })
// Your original way written out to see what is happening
// $('h1').click(console.log('Clicked')) // code below is same thing as this line
var cl = console.log("Clicked Original Way") // will log message
console.log('cl is:', cl) // cl is: undefined
$('h1').click(cl) // aka $('h1').click(undefined)
// solution 1
$('h1').click(function() {
console.log('Clicked')
})
// solution 2
function myClickFunction() {
console.log('Clicked w/ function')
}
$('h1').click(myClickFunction)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 style="text-align: center;">Some Text</h1>
Since the argument you're passing in is not a callable function, jQuery is unable to call it when the click actually happens. Try something like this:
$(document).ready(function() {
$('h1').on('click', function(e) {
console.log('clicked');
});
});
click expects a function
$('h1').click(function() {
console.log('Clicked');
});
The way you are doing it, is to output 'Clicked' and have a undefined handler "sent" to click().
Check out the documentation here
Could someone explain why the clicking on button1 doesn't get captured? I know return false on event click will stop the propagation, but it should still capture the element by document.addEventListener('click', function(e) {console.log(e.target);}); because we are trying to capture directly the main element via e.target not its parent element.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#button1").click(function(){
return false;
});
});
</script>
</head>
<body>
<button id="button1">Button1 (dont get captured)</button>
<button id="button2">Button2 (get captured)</button>
<script>
document.addEventListener('click', function(e) {
console.log(e.target);});
</script>
</body>
</html>
I can't change that jQuery code $("#button1").click(function(){return false});, but still, want to capture the button1 element when it gets clicked (with javascript), is there any workaround?
i could bind another event handler to button1 like this document.getElementById("button1").addEventListener("click", function(e){console.log(e.target)}); in real there are many many elements which I want to capture (with different classes and id), it would be impractical to add an event listener to each of them, I showed one button just for an example. , I just simply want to log whichever element is clicked.
I can't change the jQuery code or HTML of the page, i want to run some tests in chrome console only, for which i want to capture each element which is clicked
thanks
The return false; prevents the browser from performing the default action for button1 link.
The equivalent code for return false is:
$('.button1')
.click(function (event) {
event.preventDefault();
event.stopPropagation();
});
If you just want to stop propagation use stopPropagation().
Take a look at this, and read more about preventDefault() and stopPropagation()
Not very efficient but worked for me
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#button1").click(function(){
return false;
});
});
</script>
</head>
<body>
<button id="button1">Button1 (dont get captured)</button>
<button id="button2">Button2 (get captured)</button>
<script>
elements = document.querySelectorAll('body *');
elements.forEach(function(elem) {
elem.addEventListener('click', function(e){
console.log(e.target); // or simply console.log(elem)
});
});
</script>
</body>
</html>
Thanks to everyone, especially #mplungjan who gave me this idea
I have the following javascript in some pug file:
doctype html
html
//- this is not firing for some reason
head
script(type="text/javascript").
document.addEventListener('DOMContentLoaded', function() {
console.log('ready!')
}, false);
the script only runs when I refresh the page, not when I navigate to the page the script do not fire. I am looking for an event like onNavigate, however I do not see it in the list here: https://www.w3schools.com/jsref/dom_obj_event.asp or here: https://developer.mozilla.org/en-US/docs/Web/Events
Your code should work fine(if you code is written in this way). Don't see a problem.
<!doctype html>
<html>
<body>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
console.log('ready!')
}, false);
</script>
</body>
</html>
or
<!doctype html>
<html>
<body>
<script type="text/javascript">
window.onload = function() {
console.log('ready!')
};
</script>
</body>
</html>
Ya know the body OnLoad event occurs after any css and js loads - including external refs.
All you really need is:
<body onload="do_this()">
and then in the script element
function do_this(){
// do sh1t
}
In the following code I simply want the number of matched element by tag name, But it returns 0 and it alerts while page load (not on click as I want). Cannot find any mistake over an hour
<!DOCTYPE HTML>
<HTML>
<head>
<script language="javascript">
document.getElementById("all").onclick = alert( document.getElementsByTagName("a").length);
</script>
</head>
<body>
<div id="all" class="a">Click</div>
<div class="a"></div>
<div class="a"></div>
</body>
</HTML>
I'm a total newbie in JavaScript
A couple of problems. The first one is pointed by #Ian in his comment on your question and the second one is you are calling getElementsByTagName("a") when in your code you do not have any <a> tags. You need to call getElementsByClassName("a") instead.
document.getElementById("all").onclick = function() {
alert( document.getElementsByClassName("a").length);
}
Update:
After Ian's comment, double checked jsfiddle and found that it had onLoad selected. So here is the corrected code with window.onload and updated jsfiddle:
window.onload = function() {
document.getElementById("all").onclick = function() {
alert( document.getElementsByClassName("a").length);
};
};
Here is the jsfiddle of this.
You are running the JS before even DOM is loaded. That means element all does not exist in the DOM when JS is running. Write like below, and that is the way to do.
var attachEve = function(){
document.getElementById("all").onclick = function() {
alert( document.getElementsByClassName("a").length);
}
}
window.onload = attachEve;
It should work!. Without window.onload works in jsfiddle because jsfiddle runs the JS in window.onload context.