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 () {});
});
});
Related
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
I have a small problem with the #Html.ActionLink tag. I want to change the background when clicking on it. But it doesn't work.
<ul>
<li>#Html.ActionLink("View Profile", "Profile", "User", null, new { id = "profile" })</li>
</ul>
and the jQuery code:
$("#profile").click(function () {
document.getElementById("profile").style.background = "linear-gradient(#00ff66, #00ff99, #00ff66)";
});
But I have tried on w3schools, it already worked:
<!DOCTYPE html>
<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<a id="profile" href"">View profile</a>
<script>
$("#profile").click(function() {
document.getElementById("profile").style.background = "linear-gradient(#00ff66, #00ff99, #00ff66)";
});
</script>
</body>
</html>
Can you help me?
p/s: Here is my sub-question:
Can you tell me what is the different between:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<a id="profile" href"">View profile</a>
<script>
$("#profile").click(function() {
document.getElementById("profile").style.background = "linear-gradient(#00ff66, #00ff99, #00ff66)";
});
</script>
and
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$("#profile").click(function() {
document.getElementById("profile").style.background = "linear-gradient(#00ff66, #00ff99, #00ff66)";
});
</script>
<a id="profile" href"">View profile</a>
If I change the position of line <a id="profile" href"">View profile</a> to the end, the code won't work.
Why?
Answer to the main question
It is because your code is running when your page elements are not loaded. So please put script to the bottom or try the following script:
$(function () { //Since it's short and you are using jQuery. You may also use $(document).ready(function(){
$("#profile").click(function () {
document.getElementById("profile").style.background = "linear-gradient(#00ff66, #00ff99, #00ff66)";
});
});
Though you may use the above code and it works, I would recommend you to put the <script> tag always at the bottom of the page to speed up the page load time.
Anyway you can do any of these.
Answer to your sub-question:
It's because when javascript(Jquery) searches for the dom with the id you specified, if it is not loaded it gives out an error and prevents execution.
Hope it solves both of your questions.
Please accept if it is the best answer.
Keep Asking Keep Learning.
Thanks...
I think your problem is because the DOM elements are not fully loaded when the script is starting execution. You could solve the problem if wrap the script like this:
$(document).ready(function(){
$("#profile").click(function () {
document.getElementById("profile").style.background = "linear-gradient(#00ff66, #00ff99, #00ff66)";
});
});
Whenever the script executes it is looking for a dom with id = "profile" and since it hasn't loaded on the page yet, the event will not get bound.
you can fix this by wrapping your code in document ready event:
$(document).ready(function(){
//add event here
});
or in the jquery shorthand notation:
$(function(){
//add event here
});
Any code inside here will fire once your html has loaded.
Another fix to this is to place the event on the document itself and use the 'on' method to specify you are looking for #profile:
$(document).on('click', '#profile', function(){
//do stuff
});
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
I am a newbie in jquery. I am trying to create a page, which loads the contents without reloading the page. In my test page, i have 2 links i.e. link 1 and link 2. When the default page is clicked. It just says 'Hello'. When clicked on either of link, it shoud say 'Hello link1' (if link1 is clicked), 'Hello link2' (when link2) is clicked. Link1 contents(html) is in link1.html and link2 contents is in link2.html file. Whenever either of the link is clicked, it should pass name of the link's html page as parameter.
here is what i did:
<head>
<title>Ajax Practice</title>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("a").click(function test(filename){
alert(filename);
var b = $("a").attr("title");
alert(b);
//$('#menuContents').load($(filename)).fadeIn("slow");
//$('#menuContents').load('link1.html').fadeIn("slow");
$('#menuContents').load(b).fadeIn("slow");
});
});
</script>
</head>
<body>
<div id="page-wrap">
<div id="menu">
link1
link2
</div>
<div id="menuContents">
<h1>Hello!</h1>
</div>
</div>
</body>
</html>
The problem is if i just pass the name of html file as parameter, it doesn't get read as string value instead it get's read as object. The first alert in code will give [object Object] message. I can read the text from title of the link by using .attr attribute and can load the page using .load attribute. I can also change the contents of page by directly giving html page name in .load attribute (commented out in code).
Can anyone tell how i can pass name of the html page as parameter rather than hardcoding or reading through title?
Thank you.
If you are using server side scripting such as PHP you may want to look into jQuery's $.ajax()
just remove the ready() and click() function, leave the test function alone
function test(filename){
alert(filename);
//$('#menuContents').load($(filename)).fadeIn("slow");
//$('#menuContents').load('link1.html').fadeIn("slow");
$('#menuContents').load(filename).fadeIn("slow");
}
ps. in fact when you define a function in jquery click function, the function can not be called outside, you need to define the test function in gloal, then you can call it in anywhere include a.href
There is a nice way to do this below
<html>
<head>
<title>Ajax Practice</title>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("a").click(function (e){
$('#menuContents').load($(this).attr('href')).fadeIn("slow");
e.preventDefault();
return false;
});
});
</script>
</head>
<body>
<div id="page-wrap">
<div id="menu">
link1
link2
</div>
<div id="menuContents">
<h1>Hello!</h1>
</div>
</div>
</body>
</html>
$("a").click(function test(filename){
filename is in fact the event object. Please check out http://api.jquery.com/click/
Besides, in your code:
link1
will call the function test, so you can define this function in your javascript code
function test(filename){
alert(filename)
// your code here
}
Try the example here http://jsfiddle.net/WUBsq/
There are many cleaner ways you can have, for instance:
<a class="refresh" data-title="link1.html">click here</a>
...
$(document).ready(function(){
$('a.refresh').click(function(){
var title = $(this).attr('data-title');
alert(title);
// your code here
})
})
Try here : http://jsfiddle.net/WUBsq/3/
Im trying to show/hide a div using jquery when a link gets clicked. I put this in my head section:
<script type="text/javascript">
$("#attach_box").click(function {
$("#sec_box").show()
});
</script>
I have a link that looks like this:
+ Add a Postal Address (If Different)
And a div that looks like this:
<div id="sec_box" style="display: none;">
Hello world!!
</div>
This doesn't work and I can't figure out why. Any ideas?
You need to attach the click handler in the document.ready in order to make sure that the DOM has been loaded by the browser and all the elements are available:
<script type="text/javascript">
$(function() {
$('#attach_box').click(function() {
$('#sec_box').show();
return false;
});
});
</script>
Also you forgot to put parenthesis () next to the anonymous function in the click handler.
Chances are the DOM isnt fully loaded yet.
<script type="text/javascript">
$(document).ready(function()
{
$("#attach_box").click(function() {
$("#sec_box").show()
});
});
</script>
put that in your head and put your initialization code in there.