Problems with jQuery Click - javascript

I'm having a bit of trouble with jQuery, and I really have no idea what I'm doing wrong.
I have a simple page with static content and a few buttons. My problem comes when I want to attach a click event to one of my buttons - it just won't work!
Here is the code I have in my html:
<head>
<link rel="stylesheet" href="css/main.css" type="text/css">
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="js/my.js"></script>
</head>
<body>
....
<button class="btn btn-success" id="my-button">BUTTON</button>
</body>
And here is the code I have in my.js:
$('#my-button').click(function()
{
console.log("Button Clicked");
});
No matter how many times I click the button, no matter which browser I use the message is never entered to the console. I just don't get it, I've not had a problem like this before... I'm hoping it's not an obvious mistake.
I should also point out that when I change this to $(document).ready it works fine!!
Help :(

You said it your self, wrapping it in a document-ready callback will solve the problem.
The reason to this is that your JavaScript is run before the element actually is in the DOM, so at the time the JavaScript is run, no element match your selector, and therefor no clickevent-listener can be attached.
If you for some reason don't want to use a DOM-ready callback, another solution would be to include your JavaScript the last thing you do, just before you close your body element. When the browser get to that point, your element should be in the DOM, so your code should be fine.
Solution 1: Wait for DOM to be ready
$(function () {
$('#my-button').click(function() {
console.log("Button Clicked");
});
});
Solution 2: Load JavaScript last
<head>
<link rel="stylesheet" href="css/main.css" type="text/css">
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
</head>
<body>
....
<button class="btn btn-success" id="my-button">BUTTON</button>
<script type="text/javascript" src="js/my.js"></script>
</body>

Try wrapping it inside document ready function like below,
$(function () {
//content below will be executed only after DOM is ready
$('#my-button').click(function() {
console.log("Button Clicked");
});
});

This is not a mistake. Problem is when your script runs, your button is not rendered on the page. When you wrap the script in $(document).ready(), it will ensure that the script runs only after the whole content is rendered correctly.

Your js precedes your html, which means the $('#my-button') selector comes up empty. You could try event delegation, to ensure no matter when an element that matches your criteria comes into existence, there is a click listener for it:
$(document).on("click",'#my-button',function()
{
console.log("Button Clicked");
});

Related

Jquery Not Being Processed

The below Jquery does not run within my browser even though the syntax is correct( checked via online syntax checker) and the functions do run (tested with pure JS). Why is it that so?
I apologize in advance if the answer to this question is rather simple but after 15min of googling I could not arrive at an answer.
JAVASCRIPT:
document.getElementById('overlay').addEventListener('click', function( {
closeLightBox()
});
function closeLightBox() {
$("#overlay").fadeOut(1000);
}
function lightbox(x) {
}
HTML
<!DOCTYPE html>
<html>
<head>
<title> Lightbox </title>
<link rel="stylesheet" type="text/css" href="lightboxcss.css">
</head>
<body>
<div id = "overlay"> </div>
<img src="batman.jpg" alt="" href="javascript:void(0)" onclick="lightbox(1)" id="batman" style="height:100px;width:160px;margin-left:45%;margin-top:16%;">
<br><br><br><br>
<p> RANDOM TEXT STUFF </p><br><br>
<p> 328ueekfuuirgh40t43h8hohro8ht </p>
<script src="lightboxjs.js"> </script>
</body>
</html>
I assume that javascript code is located in your .js file "lightboxjs.js". Did you include the jQuery library anywhere?
If you don't, start by adding this line <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> before including your custom javascript file.
$(document).ready(function(){
//page is ready
$("#overlay").on("click",function(){
this.fadeOut(1000);
});
});
You cannot add an eventlistener if the dom isnt loaded. Also dont forget to include jquery before executing the upper script
...
Where are you calling the jquery lib? You need to load the jquery just above lightboxjs.js and may as well use jquery syntax to listen to the #overlay click event.

onload event not working. [Javascript]

I have the onclick event: onclick="javascript:_stats_content('my_bets');" which works fine.
This loads new content into a div.
However I want to set a default piece of content to load when the page loads. I have attempted to do this with the code below, but it is not working:
<body onload="myFunction()">
<script>
function myFunction() {
_stats_content('my_bets'); // have also tried with 'javascript:' infront
}
</script>
Can anyone provide any solutions?
Thanks.
EDIT:
Upon reading comments, I have added type="text/javascript".
I also replaced with an alert() and it fails to show. I should note that I am using AngularJS to display the page so this might interfere. However the first onclick example works fine on the page, so I don't understand how onload would be any different.
EDIT2: This is an extract of code from the top of the page:
<head>
<script type="text/javascript">
function myFunction() {
alert("Hello! I am an alert box!!");
}
</script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="content/ext/msgbox/Scripts/jquery.msgBox.js"></script>
<link rel="stylesheet" type="text/css" href="content/ext/msgbox/Styles/msgBoxLight.css">
<script type="text/javascript" src="content/ext/qtip/jquery.qtip.min.js"></script>
<link rel="stylesheet" type="text/css" href="content/ext/qtip/jquery.qtip.min.css">
<script type="text/javascript" src="js/colors.js"></script>
<?php include './js/includer.php'; ?>
</head>
<body onload="myFunction()">
I have replaced with an alert to make it easier to troubleshoot, although the alert is still not showing. I think it's just an AngularJS related issue, guess I'll just have to figure this out.
Whilst I wasn't able to get this exact method to work, the reason for which I still have no idea. I imagine it's AngularJS interfering.
I used:
<img src="87.jpg" onload="javascript:_stats_content('my_bets');" width="0" height="0">
Just before the </body> tag and that worked.

JavaScript not working as an external file

I'm new to HTML, JavaScipt and everything related to programming, and I'm trying to create a simple page.
Now, I'm stuck with the following problem: I want to change the date of my main.html file, but the main.js is not working. I've already change the <script> position to inside the <body>, after the </span> and even after the </body>, without success. If the content of the main.js is within the HTML it works fine, but as a external file it doesn't.
Here is my main.html:
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="main.js"></script>
<title>Page 1</title>
</head>
<body>
<p>WRF<br>
<span id="data">18/09/1987</span></p>
</body>
</html>
My main.js is just:
document.getElementById("data").innerHTML = "JUBA";
I've looked through the internet and through this forum, but all answers that I've found did not worked.
The files are on the same directory and the main.css works fine.
Thank you in advance.
At time you call main.js element #data was not created in DOM tree. You can fix this by putting the link to your Javascript file right before closing the body like this:
<script type="text/javascript" src="main.js"></script>
</body>
Document Object Model (DOM) is not "READY".
Try use onload event, inside main.js:
window.onload = function() {
document.getElementById("data").innerHTML = "JUBA";
};
If needs more "fast" than onload, use jquery with $(document).ready:
html:
<link href="main.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="main.js"></script>
main.js:
$(document).ready(function() {
$("#data").html("JUBA");
});
window.onload vs $(document).ready()
Answer by #Guffa:
The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.
The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.
The element is not yet accessible when you run the script.
Either you can put the script at the end of the page or delay the execution.
You could put the JavaScript in the <body> tag after the rest of the page. When the browser loads it, the <span> will already be there to be edited.
As per your code the script will be called first then page will be loaded, therefore when the script is running there will not be any element having id data because yet page have to be loaded. There are many ways to achieve what you need.
1. Add a script tag before or after end of body like
or
<script type="text/javascript" src="main.js"></script>
</body>
Write .js file above before body i.e. in head tag and write the whole javascript code in onload method.
window.onload=function(){
document.getElementById("data").innerHTML = "JUBA";
};
window.onload=function(){
document.getElementById("data").innerHTML = "JUBA";
};
<p>WRF<br>
<span id="data">18/09/1987</span></p>

Loading page into div causes page's javascript to not work

I am loading a page into a div by
<script>
$(document).ready(function() {
$("#link").click(function(e) {
e.preventDefault();
$("#div").load("page.php");
});
</script>
The page loads but the javascript that I have in page.php does not load.
This is what I have:
<script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
$(function() {
$("#date").datePicker();
});
</script>
When I load page.php outside of the div (as in its own tab/window), the page works perfectly. (The above is copy-pasta from http://jqueryui.com/datepicker).
What is the cause and how can I solve it?
Your scripts are never loaded. They are stripped out during load.
(The above is copy-pasta from http://jqueryui.com/datepicker/)
I'm going to assume that you mean you are copying the entirety of that sample's source, which looks roughly like this:
<!doctype html>
<html lang="en">
<head>
<!-- Snipped for brevity: A bunch of script and link elements-->
</head>
<body>
<p>Date: <input type="text" id="datepicker" /></p>
</body>
</html>
So you're taking this document using jQuery's load function and placing it inside a div:
$("#div").load("page.php");
Load won't cooperate here
According to the docs on .load():
jQuery uses the browser's .innerHTML property to parse the retrieved document and insert it into the current document. During this process, browsers often filter elements from the document such as <html>, <title>, or <head> elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser.
In my own experience, this normally means that .load() will only return content from inside the body element, without the body element itself. In other words, from the above sample, this is the only HTML actually being loaded:
<p>Date: <input type="text" id="datepicker" /></p>
You should use your browser's developer tools (F12) to put a breakpoint in the script and find out what actually gets loaded.
How do you do this properly?
There's two parts to it.
Part 1: Move resources outside the <head> element
The Datepicker code sample contains a few resources in the <head>. You're going to have to place these elsewhere.
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
The link elements
These can't be loaded up by the page you're loading. Place those inside the <head> element of the parent page you're trying to load this other one into.
The script elements
These will be loaded up when you load the document, too, as long as:
You place them within the <body> element of the document you're loading, and
You adhere to this section in the jQuery .load() docs to make sure you load in the script elements correctly.
However, it's only jQuery and jQuery UI, which you know you're going to be using. You might as well move these into the parent page's <head> element too.
2. Place the important bits you're trying to load in the body.
That's these bits:
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
<p>Date: <input type="text" id="datepicker" /></p>
Place those inside the <body> element of the document you're trying to load. Then, provided you followed that advice about scripts, this will be loaded successfully.
Optionally, include jQuery references in the <body>:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
<p>Date: <input type="text" id="datepicker" /></p>
You may just need to change:
<script>
$(function() {
$("#date").datePicker();
});
</script>
to
<script>
$("#date").datePicker();
</script>
as the document.ready event has already fired, which is what $(function() { tells it to wait for. I'm not sure if jquery automatically runs scripts in ajax'ed content, if not, you could try this (not neccessarily safe, make sure you understand the security risks of eval if you do this).
$("#div").load("page.php", function() {
$("#div").find("script").each(function(i) {
eval($(this).text());
});
});
Note: this will run something like:
<script>
$("#date").datePicker();
</script>
But NOT something like:
<script>
$(function() {
$("#date").datePicker();
});
</script>
As, again, the second waits for the document.ready event, which has already fired.
I think $(document).ready() aka $(function) will not execute when you load the document with load.
You can try to trigger it manually in the complete callback of load, or you can name the function you pass to $ and call it.

css not being applied to document.write text

I'm writing text to a page using document.write for a Chrome extension, but the associated custom CSS isn't applied:
<!DOCTYPE html>
<html>
<head>
<title>TITLE GOES HERE</title>
<link rel="stylesheet" href="css/popup.css" type="text/css" />
</head>
<body>
<script type="text/javascript">
...
function showFolder(folder) {
console.debug('FOLDER: '+folder.title);
document.write('<p>'+folder.title+'<br></p>');
}
</script>
</body>
</html>
The CSS is simple, just for debugging:
p {
color: red;
}
I can get it to work if I put the stylesheet link inside the function showFolder, but that can't be the proper way to do it. I'm learning jscript/CSS on the fly, so the answer is probably something remedial. Is the problem in the jscript, the CSS or both?
Use innerHTML.
<div id="towrite"></div>
then you can write in it like this:
div=document.getElementById('towrite');
div.innerHTML = '<p>'+folder.title+'<br></p>';
If you run your document.write() before the page finishes loading (perhaps calling your showFolder call directly from a script on the page), then the text will be written into the document as you might expect.
However, if you call document.write after the page loads, as in an event handler, you will be writing an entirely new page. This is usually not what you want.
Instead, follow Zoltan's advice and set the innerHTML property of an empty div.
I'm not javascript expert... I mainly use jQuery.. but try this, kind of makes sense:
<!DOCTYPE html>
TITLE GOES HERE
<script type="text/javascript">
...
function showFolder(folder) {
console.debug('FOLDER: '+folder.title);
document.write('<p>'+folder.title+'<br></p>');
}
</script>
<link rel="stylesheet" href="css/popup.css" type="text/css" />
EDIT:
So the above didn't work, but I just thought about another solution. When are you actually calling the function? Try to put it in <body onLoad="functionnamehere()">
No idea if that works, but give it a try.

Categories