My test.jsp file:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script type="text/javascript" src="js/test.js"></script>
</head>
<body>
<a href='#' id='mylink'>click me</a>
</body>
</html>
My test.js file:
alert("HELLO");
var myLink = document.getElementById('mylink');
myLink.onclick = function(){
alert("I am a pop up ! ");
}
When I load the test.jsp page the Hello alert appears just fine. However when I click on click me, nothing happens.
At the point your script is running, the rest of the DOM hasn't been created yet.
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
</head>
<body>
<a href='#' id='mylink'>click me</a>
<script type="text/javascript" src="js/test.js"></script>
</body>
</html>
Moving the script tag to the bottom is one way to fix that.
It works fine here. Try wrapping it in an onload event listener to ensure the DOM is ready when the document.getElementById is called on the mylink element.
window.addEventListener("load", function()
{
var myLink = document.getElementById('mylink');
myLink.onclick = function() {
alert("I am a pop up ! ");
}
});
<a href='#' id='mylink'>click me</a>
This is a common issue of timing on how things are loaded into the browser on your page. The browser will run scripts and load HTML as it encounters it from the top down. Your JS file is running at the very top of the page. This means, at the point of its execution, the A HREF tag doesn't exist when you create the onclick event. The big issue is that when you call this line:
document.getElementById('mylink');
That A HREF tag doesn't yet exist, because the browser hasn't yet made it down the page to that line to load the tag into memory (again, because your JS file is at the top of the page). It's a timing issue. That function call returns null, effectively.
You need to put the event handler creation either on an body.onload event or, since you are using the jQuery library, inside a document.ready event. This delays the onclick event creation until the tag is loaded into memory and ready. For example:
$(document).ready(function() {
var myLink = document.getElementById('mylink');
myLink.onclick = function(){
alert("I am a pop up ! ");
}
});
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 have some very simple code below that listens for an event (a click on an anchor tag). It works fine if I create a standalone html file. But if I create a file for just the script, register and enqueue it and then add that anchor tag to a Wordpress page, nothing happens when I click it. I can see in the console that the script file was loaded. I get no error when I click the link but neither do I get the results from the script. Do I have my anchor tag written correctly? Where is my error?
<html>
<head>
<script language="javascript" type="text/javascript" src="/wp-includes/js/jquery/jquery.js"></script>
</head>
<body>
Click here
<script id="source" language="javascript" type="text/javascript">
var $j = jQuery.noConflict();
$j( ".citation" ).click(function ( )
{
event.preventDefault();
// do stuff
});
</script>
</body>
</html>
event is not defined. Make it as an argument
$j(".citation").click(function(event) {
event.preventDefault();
// do stuff
});
I'm working on a simple chrome extension that displays a string of text when the user opens a new tab. The code is:
<html>
<head>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="showText.js"></script>
</head>
<body>
<div id="textDiv">
<h1 id="actualText"></h1>
</div>
<div id="footer">
<img src="settings.png"/>
</div>
</body>
</html>
and the js file
document.addEventListener("DOMContentLoaded", function () {
var text = "sample text";
$('#actualText').append(text);
});
This doesn't seem to work when I open a new tab, but when I click refresh on the tab, the text shows up. So I'm guessing the first time the DOMContentLoaded event has already been fired before this code is run? That shouldn't be the case if I load it in the head though right? I'd appreciate any help!
If you are using jquery just do:
$(function () {
var text = "sample text";
$('#actualText').append(text);
});
This will call the function when the document is ready. Apparently this is equivalent to DOMContentLoaded
The following code is a test piece. Normally the href in the Link would point to "http://www.google.com/", but the attr should change it to reference "http://maps.google.com" BUT, the reference is not changing. Can anyone tell me why it is not working? Thanks
<html>
<head>
<script type="text/javascript">
$("a#changeme").attr('href',
'http:\/\/maps.google.com/');
</script>
</head>
<body>
<div class="content">
<p>Link to <a href="http://www.google.com/"
id="changeme">Google</a>
in the content...</p>
</div>
</body>
</html>
jQuery is not loaded.
If it was, you would have to wrap it in a $(document).ready handler.
This can be done without jQuery.
Code:
window.onload = function() {
document.getElementById("changeme").href = 'http://maps.google.com/';
};
The onload handler is not exactely equal to the DOMContentLoaded handler, but it has a better support, and may be preferred here. Alternatively, you can move the <srcipt> block to the end of the <body>, and then use the method without any onload handlers:
<body>
<div class="content">
<p>Link to Google
in the content...</p>
</div>
<script type="text/javascript">
// This code is placed after the element, so the reference does exist now.
// In the head, the same code will throw an error, because the body doesn't
// even exist.
document.getElementById("changeme").href = 'http://maps.google.com/';
</script>
</body>
The script is in the header so it's executed before the other content has been loaded (if jQuery is even active, seeing no reference to it). You should put it in a function and then call it later on (e.g. through onload or a timer). I could as well think of a security feature in the browser, to keep sites from manipulating links right before you click on them.
Here is the code for the correct jQuery way to do this (using the document ready).
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#changeme").attr('href', 'http:\/\/maps.google.com/');
});
</script>
</head>
<body>
<div class="content">
<p>Link to <a id="changeme" href="http://www.google.com/">Google</a>
in the contenttest...</p>
</div>
</body>
</html>
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/