I have a simple single page setup. Under a root folder, I have 3 subfolders (js, css, and images). In the root folder, I have an index.html page with the following content:
<html>
<head>
<title></title>
<script language="javascript" src="js/jquery-1.3.2.min.js"></script>
<script language="javascript" src="js/myscript.js"></script>
</head>
<body>
<a onclick="doSomething()" href="#" class="doSomething">Click!</a>
</body>
<html>
myscript.js contains the following code:
$('a.doSomething').click(function(){
//Do Something here!
alert('You did sometihng, woo hoo!');
});
When I click the link, nothing happens. What am I missing?
Wrap document.ready around the code:
$(document).ready(function() {
$('a.doSomething').click(function(){
//Do Something here!
alert('You did sometihng, woo hoo!');
return false; // return false to prevent default action
});
});
As it is right now, you are trying to bind an event to an element that does not yet exist in the DOM.
Also, not sure why you have the onclick on the link itself, as the whole point of jQuery is to be able to take those ugly inline events out of there and bind them cleanly in the javascript. If you do this:
yay click me
And then use the code above, it should work fine.
At first I thought you were just missing a function named "doSomething". Then I realized you where expecting your selector to find the anchor tag anyway. However, that won't happen. At the time your script runs, the anchor hasn't been added to the DOM yet.
Related
I have created two short javascript files, each containing a $(document).ready function that has javascript to detect a button click from the html file that has included it. My main html file has the script tags pointing to each file in the header:
file1.js:
$(document).ready(function(){
$('.wrapper').on('click', '.click_1', function(){
alert('hello from the first file');
});
});
file2.js:
$(document).ready(function(){
$('.wrapper').on('click', '.click_2', function(){
alert('hello from the second file');
});
});
My goal, however, is to be able to dynamically remove one of the script tags (the javascript from the second file) from the header, and its functionality along with it. To do so, I created a script in my main html file to remove the target script tag via the src attribute. However, while an inspection of the page source reveals that the third script tag has indeed been removed, its functionality remains. For instance, even after clicking the .remove_2 button, I can still click the .click_2 button and receive the "hello from the second file" alert:
main.html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="file1.js"></script>
<script type="text/javascript" src="file2.js"></script>
</head>
<body>
<div class="wrapper">
<button class='click_1'>File1</button>
<button class='click_2'>File2</button>
<button class='remove_2'>Remove File2</button>
</div>
</body>
<script>
$(document).ready(function(){
$('.wrapper').on('click', '.remove_2', function(){
$('script[src="file2.js"]').remove();
});
});
</script>
</html>
In short, I wish to be able to dynamically remove a script tag so that the javascript in the file that the tag points to no longer has any affect on the html page. However, I have not been able to accomplish this. Can anyone tell me what is wrong with my code? Also, is what I am trying to accomplish even possible? Thank you.
Removing an external script does not remove event handlers. They are attached to current document.
A solution can be:
remove the script
get all html page
replace html page with new content
$('.wrapper').on('click', '.remove_2', function(){
$('script[src="file2.js"]').remove();
var html = document.documentElement.innerHTML;
document.open('text/html');
document.write(html);
document.close();
});
In jQuery, replacing only the header after removing the script:
$('.wrapper').on('click', '.remove_2', function(){
var header = $('html head');
header.find('script[src="file2.js"]').remove();
$('html head').replaceWith(header);
});
Try unbinding the click event from the second button before removing it:
$('.click_2').unbind("click");
Although unbind is now deprecated. The newer form is 'off':
$('.click_2').off( "click", "**" );
http://api.jquery.com/off/
That said, you do seem to be using a rather peculiar approach to disable click functionality.
I dont want to reveal html page content if one specific javascript is not fully loaded. I want to show blank page when this javascript is loading. Javascript is located in .js file, so in html page it looks like this:
<script src = "file.js"></script>
Put the script tag into the head element of the html document, e.g.
<!doctype html>
<html>
<head>
<script src="file.js"></script>
</head>
<body>
</body>
</html>
This depends on whether file.js performs asynchronous operations.
If your file contains simple, synchronous code, a hackish solution would be to put document.body.style.display="none" at the start of the code and document.body.style.display="block" at the end. This will hide your document body until the script reaches the end.
A more robust solution would be to make sure all your code is in appropriate functions, and wrap the initial function with a callback that displays the body.
window.onload = runOnLoad( function() { document.body.style.display="block"; } );
function runOnLoad( callback ) {
document.body.style.display="none";
// rest of your code
callback();
}
I have tried finding an answer to this on my own, but only found instructions on how to use onload events. I seem to be missing the point.
I've been taught that if I want something to happen when the page loads, I should use window.onload like this:
<script>
window.onload = dosomething();
function dosomething()
{
window.alert('hello');
}
</script>
But now that I am thinking on my own I wonder what the point of doing that is. Because this also produces the same result:
<script>
dosomething();
function dosomething()
{
window.alert('hello');
}
</script>
Anything I put at the top inside <script> is going to execute anyway... so what's the point of window.onload?
If you're directly running your code with dosomething();, you're delaying your browser's rendering for the time it takes your JavaScript code to run.
You can try to insert your code to the <head> of your html document:
<!DOCTYPE html>
<html>
<head>
<script>
dosomething();
function dosomething()
{
window.alert('hello');
}
</script>
</head>
<body>
Does not render before the alert is dismissed!
</body>
</html>
You'll see that the page stays blank until you dismiss the alert. So every second the browser takes to run your JavaScript code is a second that your users have to wait for the site to be rendered.
Now if you change the code to be run on body's onload, the page gets rendered before the alert is shown:
<!doctype html>
<html>
<head>
<script>
function dosomething()
{
window.alert('hello');
}
</script>
</head>
<body onload="dosomething()">
This page gets rendered before the alert!
</body>
</html>
Consider these two blocks of code:
<head>
<script>
alert(document.getElementById('foo').value);
</script>
</head>
<body>
<input id="foo" value="hello">
</body>
<head>
<script>
window.onload = function() {
alert(document.getElementById('foo').value);
}
</script>
</head>
<body>
<input id="foo" value="hello">
</body>
In the first example, we'll get an error because the element you are referencing isn't found when the script runs - and so you are trying to get value of null.
In the second example, document.getElementById() will find the element with the id foo, because window.onload will get fired only when the complete DOM has been loaded and so the element is available.
window.onload will fire once the DOM has finished loading. In your example, the DOM is not required. However, the following code will fail if the DOM has not yet loaded:
function doSomething() {
alert(document.getElementById('test').innerText);
}
// Throws: TypeError: Cannot read property 'innerText' of null
Assuming your page contains an element with id test, it will alert its text.
waiting for the onload event assures you that all of your scripts and resources are loaded
Assume you are using jquery in your page and you invoked a function that uses it directly without onload , you can't guarantee that the jquery file has been loaded, which will lead to errors and possibly ruining your whole logic
The onload event is handy to make sure the page is fully loaded before you run a script. For your example above it doesn't make sense, but if your page is still loading an item on the bottom and you try to call it then nothing will run.
I recommend using jQuery and using the ready function. This way you will ensure your page is completely loaded.
$( document ).ready(function() {
// This will only run after the whole page is loaded.
});
If you don't want to load query, just put your javascript at the bottom of the page. It's best practice, and ensures the DOM is loaded in full.
For more info on the jquery ready function go here: https://api.jquery.com/ready/
I wrote a small page with jQuery and an external .js file. But it won't load the jQuery part. Here my Code:
<!DOCTYPE html>
<head>
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/testScript.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<button id="testBtn">Oh my Goood...</button>
<div id="testDiv">testText</div>
</body>
</html>
And here is my external Script:
alert("no jQuery");
$("button#testBtn").click(function(){
alert("Works!");
});
As you can see, jQuery will load before all other scripts. The alert pops up fine. But if I click the button, nothing happens. If I put the script inside the html document directly, the button event works as expected.
I reviewed these questions: Link and Link. But still not working as expected.
Instead of using the $(document).ready() method, you could also just move your javascript references to the bottom of the page, right above the </body> tag. This is the recommended way to include javascript in webpages because loading javascript blocks the page rendering. In this case it also makes sure the elements are already rendered when the javascript is executed.
You'll need to add the click function inside document ready.
$(document).ready(function(){
$("button#testBtn").click(function(){
alert("Works!");
});
});
Your method fails because the code is being executed as the page is being loaded and the elements it refers to haven't been loaded yet. Using $(document).ready holds the function execution till the DOM elements are ready.
Code:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
$("#clicker").click(function () {
alert("Hello!");
$(".hide_div").hide();
});
</script>
The above code doesn't work. When I click on #clicker, it doesn't alert and and it doesn't hide. I checked the console and I get no errors. I also checked to see if JQuery was loading and indeed it is. So not sure what the issue is. I also did a document ready function with an alert and that worked so not sure what I am doing wrong. Please help. Thanks!
You are supposed to add the javascript code in a $(document).ready(function() {}); block.
i.e.
$(document).ready(function() {
$("#clicker").click(function () {
alert("Hello!");
$(".hide_div").hide();
});
});
As jQuery documentation states: "A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute"
I found the best solution for this problem by using ON with $(document).
$(document).on('click', '#yourid', function() { alert("hello"); });
for id start with see below:
$(document).on('click', 'div[id^="start"]', function() {
alert ('hello'); });
finally after 1 week I not need to add onclick triger.
I hope this will help many people
Your code may work without document.ready() just be sure that your script is after the #clicker. Checkout this demo: http://jsbin.com/aPAsaZo/1/
The idea in the ready concept. If you sure that your script is the latest thing in your page or it is after the affected element, it will work.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<a href="#" id="clicker" value="Click Me!" >Click Me</a>
<script type="text/javascript">
$("#clicker").click(function () {
alert("Hello!");
$(".hide_div").hide();
});
</script>
</body>
</html>
Notice:
In the jsbin demo replace http with https there in the code, or use this variant Demo
Try adding $(document).ready(function(){ to the beginning of your script, and then });. Also, does the div have the id in it properly, i.e., as an id, not a class, etc.?
You have to wrap your Javascript-Code with $(document).ready(function(){});Look this JSfiddle.
JS Code:
$(document).ready(function() {
$("#clicker").click(function () {
alert("Hello!");
$(".hide_div").hide();
});
});
Be sure there is nothing on your button (such a div or a trasparent img) that keeps from clicking the button.
It sounds stupid, but sometimes we think that jQuery is not working and all that stuffs and the problem is on the positioning of DOM elements.
You can use $(function(){ // code }); which is executed when the document is ready to execute the code inside that block.
$(function(){
$('#clicker').click(function(){
alert('hey');
$('.hide_div').hide();
});
});
Just a quick check, if you are using client-side templating engine such as handlebars, your js will load after document.ready, hence there will be no element to bind the event to, therefore either use onclick handler or use it on the body and check for current target
Proper Browser Reload
Just a quick check as well if you keep your js files separately: make sure to reload your resources properly. Browsers will usually cache files, so just assure that i.e. a former typo is corrected in your loaded resources.
See this answer for permanent cache disabling in Chrome/Chromium. Otherwise you can generally force a full reload with Ctrl+F5 or Shift+F5 as mentioned in this answer.