I would like to display the updated Anchor/Hash in id="demo" when a link is clicked. The layout of the document is as follows.
<html>
<head>
<script type="text/javascript">
function myfunction()
{
document.getElementById("demo").innerHTML=location.hash;
}
</script>
</head>
<body>
<h1>Javascript</h1>
<p id="demo">This is a paragraph.</p>
here
</body>
</html>
Only problem is when the link is clicked the javascript does not get the updated Anchor/Hash until the link is pressed for a second time.
It is because the location hasn't changed at this time. Here is a way you can use:
function myfunction() {
// Sets the event handler once you click, so it will execute when
// the hash will change.
window.onhashchange = function() {
document.getElementById("demo").innerHTML=location.hash;
};
}
A modern way would be:
var hashchange;
function myfunction() {
if ( !hashchange ) {
hashchange = addEventListener( 'change', function() {
document.getElementById("demo").textContent = location.hash;
// If you want to remove the event listener right after,
// you can do this:
removeEventListener( hashchange );
}, false );
}
}
Try this JQuery plugin for detecting the hash change:
http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/
It's open-source, so check out the code, which is surprisingly complex-- 300+ lines (annotated, but still).
Try this:
function myfunction() {
setTimeout(function() {
document.getElementById("demo").innerHTML=location.hash;
}, 1);
}
because when you click in the link the hash is still your prevous one so you need a delay.
It is because "location" refers to an anchor WITHIN the page.
The first click, you have no location within the page, but the anchor takes you to #example, but all this happens after the onclick has done its business. The second click we have a location of #example.
See the W3 Schools documentation here.
The onclick event is fired before the anchor has had chance to do its job. This is crucial to being able to cancel the propagation of the event and prevent redirection etc. but sadly knobbles your code.
Related
I have a link:
<ul id="titleee" class="gallery">
<li>
Talent
</li>
</ul>
and I am trying to trigger it by using:
$(document).ready(function() {
$('#titleee').find('a').trigger('click');
});
But it doesn't work.
I've also tried: $('#titleee a').trigger('click');
Edit:
I actually need to trigger whatever get's called here <a href="#inline" rel="prettyPhoto">
If you are trying to trigger an event on the anchor, then the code you have will work I recreated your example in jsfiddle with an added eventHandler so you can see that it works:
$(document).on("click", "a", function(){
$(this).text("It works!");
});
$(document).ready(function(){
$("a").trigger("click");
});
Are you trying to cause the user to navigate to a certain point on the webpage by clicking the anchor, or are you trying to trigger events bound to it? Maybe you haven't actually bound the click event successfully to the event?
Also this:
$('#titleee').find('a').trigger('click');
is the equivalent of this:
$('#titleee a').trigger('click');
No need to call find. :)
Sorry, but the event handler is really not needed. What you do need is another element within the tag to click on.
<a id="test1" href="javascript:alert('test1')">TEST1</a>
<a id="test2" href="javascript:alert('test2')"><span>TEST2</span></a>
Jquery:
$('#test1').trigger('click'); // Nothing
$('#test2').find('span').trigger('click'); // Works
$('#test2 span').trigger('click'); // Also Works
This is all about what you are clicking and it is not the tag but the thing within it. Unfortunately, bare text does not seem to be recognised by JQuery, but it is by vanilla javascript:
document.getElementById('test1').click(); // Works!
Or by accessing the jQuery object as an array
$('#test1')[0].click(); // Works too!!!
Since this question is ranked #1 in Google for "triggering a click on an <a> element" and no answer actually mentions how you do that, this is how you do it:
$('#titleee a')[0].click();
Explanation: you trigger a click on the underlying html-element, not the jQuery-object.
You're welcome googlers :)
If you are trying to trigger an event on the anchor, then the code you have will work.
$(document).ready(function() {
$('a#titleee').trigger('click');
});
OR
$(document).ready(function() {
$('#titleee li a[href="#inline"]').click();
});
OR
$(document).ready(function() {
$('ul#titleee li a[href="#inline"]').click();
});
With the code you provided, you cannot expect anything to happen. I second #mashappslabs : first add an event handler :
$("selector").click(function() {
console.log("element was clicked"); // or alert("click");
});
then trigger your event :
$("selector").click(); //or
$("selector").trigger("click");
and you should see the message in your console.
Well you have to setup the click event first then you can trigger it and see what happens:
//good habits first let's cache our selector
var $myLink = $('#titleee').find('a');
$myLink.click(function (evt) {
evt.preventDefault();
alert($(this).attr('href'));
});
// now the manual trigger
$myLink.trigger('click');
This is the demo how to trigger event
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("input").select(function(){
$("input").after(" Text marked!");
});
$("button").click(function(){
$("input").trigger("select");
});
});
</script>
</head>
<body>
<input type="text" value="Hello World"><br><br>
<button>Trigger the select event for the input field</button>
</body>
</html>
This doesn't exactly answer your question, but will get you the same result with less headache.
I always have my click events call methods that contain all the logic I would like to execute. So that I can just call the method directly if I want to perform the action without an actual click.
For links this should work:
eval($(selector).attr('href'));
You should call the element's native .click() method or use the createEvent API.
For more info, please visit: https://learn.jquery.com/events/triggering-event-handlers/
We can do it in many ways...
CASE - 1
We can use trigger like this : $("#myID").trigger("click");
CASE - 2
We can use click() function like this : $("#myID").click();
CASE - 3
If we want to write function on programmatically click then..
$("#myID").click(function() {
console.log("Clicked");
// Do here whatever you want
});
CASE - 4
// Triggering a native browser event using the simulate plugin
$("#myID").simulate( "click" );
Also you can refer this : https://learn.jquery.com/events/triggering-event-handlers/
Shortest answer:
$('#titlee a').click();
I've been trying to figure out if it's possible to dynamically change the src of a <script> tag (or load a new script tag) and have the previous script no longer execute. Example below:
index.html
<button id="action">Click</button>
<script id="javascript-file-script" type="text/javascript" src="/js/oldjsfile.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#javascript-file-script").remove();
setTimeout(function() {
$('body').append('<script id="javascript-file-script" src="/js/newjsfile.js" type="text/javascript"><\/script>')
}, 100);
});
</script>
oldjsfile.js
$(document).ready(function() {
console.log('old file loaded');
$('#action').click(function() {
alert('old');
});
});
newjsfile.js
$(document).ready(function() {
console.log('new file loaded');
$('#action').click(function() {
alert('new');
});
});
Before changing the javascript file, clicking on #action would have 1 alert "old". Once I change the script, and click on #action I get both alerts "old" and "new". Is there a way to "unload" the previous file so that the original click function is removed/not executed?
I'm looking for a solution other than changing ids or editing the scripts. I'm thinking this isn't possible because the script is already in memory.
That isn't possible. It is already loaded and running. You should consider using .on and .off for binding to the click event.
To begin, you definitely do not want to load and unload scripts as that will cause other problems and loading scripts should be done asynchronously.
For your first event, you did everything fine.
For the second event, it has to happen when something else happens. In my snippet below, I created another button and when that was clicked it took off the old event and added the new one. This doesn't have to happen on button click it can be on anything but you have to remove the old event with unbind and create a new one just like you did originally.
To try the example below, click the first button and you'll see an alert of 'old'. Then click on the second button and click on the first button again and you'll see 'new'.
$(document).ready(function () {
// The original click event.
$('#action').click(function () {
alert('old');
});
// Let's set up a reference to our new button which will cause the #action click to change.
$('#changeAction').click(function () {
// Unbind the previous click event associated with #action:
$('#action').unbind('click');
// Create the new click event.
$('#action').click(function () {
alert('new');
});
});
});
<button id="action">Click</button>
<button id="changeAction">Click me to change the action of the first button</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have a problem with anchor tag i fill my html table with append jQuery and inside a td there is anchor tag when i click on it instead of calling it's function it refresh the page:
$('.show-directions').click(function( event ) {
event.preventDefault();
$('.ui.modal').modal('show');
setTimeout(function() {
initMap();
}, 500);
});
function initMap(){
console.log("initMap has been called.");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<a class="show-directions" href="">Detail</a>
Change your code to the following:
$(document).on('click', '.show-directions', function(){
//YourCode
});
And it should work.
For an explanation of the problem, read #Optimus Prime answer's here: Why doesn't click work on appended elements?
I did something else
<a class="show-directions" href="javascript:tacos();" >
and i called the function tacos which has do the same thing
function tacos () {
$('.ui.modal').modal('show');
setTimeout(function() {
initMap();
}, 2000);
}
As you can see (after my edit to your question), assuming you have properly referenced the Bootstrap library, your code is working as it should. Your issue therefore must be with something else on the page.
You've indicated that you are dynamically adding the a element with .append(). In this case, the click event handler is being registered before the element has been added to the document. To ensure that it is handled, use "event delegation", which is the process of setting up the event handler on a higher level element (that exists at the time of the event registration) in the document and then when the event is later initiated by a lower-level element, event bubbling causes it to arrive at the higher element. You then check to see what element initiated the event.
Having said all of this, you should not use an a for this in the first place. <a> elements are for navigation, not for hooks into JavaScript. It is semantically incorrect to use a hyperlink for non-navigational tasks. It will cause problems for users who use assitive technologies (like screen readers) to surf the web, and (as you already know, given your code) requires you to disable the browser's native desire to navigate by adding event.preventDefault().
Instead use some other element to trigger your function, like a span element:
// Intercept the event at the document level, but check to see if
// it originated with an element that has the .show-direcions class
$(document, '.show-directions').click(function( event ) {
$('.ui.modal').modal('show');
setTimeout(function() {
initMap();
}, 500);
});
function initMap(){
console.log("initMap has been called.");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<span class="show-directions">Detail</span>
Add this in script $(function(){$("#AnchorTagID").click(function(){return false;});}); or use <button type='button'>Add Anchor Attributes here<button/>
Or instead you can add href="#" instead of empty href or entirely remove it from there.
I want to attach a jQuery event handler to a <div> element such that whenever a link is clicked which points to this <div>, that handler is activated and the associated function is executed – regardless of the location of the link (same page, other page, other site) pointing to the <div> .
$("div#mydiv").on("linked_to", function(){ //is there a "linked_to" event?
//do something about it
});
Is this possible? Can scrollIntoView() be used?
What you want is quite specific and borderline undoable. I think your best bet is to detect a hash change in the URL and act accordingly.
You aren't gonna be able to detect that div#mydiv itself was clicked, but detecting the hash #mydiv comes pretty close to it.
You would use something like:
window.onhashchange = function() {
if (window.location.hash === '#mydiv') { // here you check if it was `#mydiv`
alert('hey! are you after mydiv?!')
}
}
Check an example here: http://output.jsbin.com/pikifov - click the link and notice how the hash from the URL changes.
Source for the JSBin above here.
Full code:
<div id="mydiv">mydiv</div>
<hr>
Click to go to mydiv
<script>
window.onhashchange = function() {
if (window.location.hash === '#mydiv') {
alert('hey! are you after mydiv?!')
}
}
</script>
I am trying to achieve this task using MooTools.
Description:
I attached an event listener to myButton link. A click on this link initiates an AJAX request and updates myDiv content based on the response text.
During this request a POST variable is being sent to "button.php", but it's not used at the moment.. (i wish to use it later)
OK, as a result, myDiv gets exactly the same link with the same ID (myButton) + a random number, so that we could see that each click generates a new number.
The problem:
After the first click on myButton, myDiv updates correctly, showing a random number. When I click myButton for the second time (this time in newly updated div), the div does not refresh anymore.
Please note that I need myButton to be inside myDiv, and myDiv must be updated (refreshed) after each click without having to refresh the entire page.
Can somebody show me how to achieve this task based on this simplified code example?
index.html
<html>
<head>
<script type="text/javascript" src="mootools-1.2.4-core-nc.js"></script>
<script>
window.addEvent('domready', function() {
$('myButton').addEvent('click', function(e) {
e.stop();
var myRequest = new Request({
method: 'post',
url: 'button.php',
data: {
action : 'test'
},
onRequest: function() {
$('myDiv').innerHTML = '<img src="images/loading.gif" />';
},
onComplete: function(response) {
$('myDiv').innerHTML = response;
}
});
myRequest.send();
$('myButton').removeEvent('click');
});
});
</script>
</head>
<body>
<div id="myDiv">
<a id="myButton" href="#">Button</a>
</div>
</body>
</html>
button.php
<a id="myButton" href="#">Button</a> clicked <?php echo rand(1,100); ?>
Look at Element.Delegation to setup the event on the myDiv container one time, so you don't have to re-attach handlers each time the contents are updated. You need to include this MooTools-More extension in your scripts as it's not part of core yet, but will be starting from version 1.3.
$("myDiv").addEvent("click:relay(a)", function() {
...
);
If you have multiple <a> links inside, and you only want to delegate a specific subset of those, add a class or some other property to distinguish them. You can use almost any selector inside relay(..). Let's say all links had a class updateTrigger added to them:
<a class="updateTrigger" id="myButton" href="#">Button</a>
the syntax would then be:
$("myDiv").addEvent("click:relay(a.updateTrigger)", function() {
...
});
See this working example where links are replaced every 5 seconds. There is only one event setup on the myDiv container and it handles all clicks to all <a>s, even the dynamic ones.
you are attaching an event to an element that you are replacing. the dom has no way of knowing that to you, the old and the new button are identical. The old button is deleted (and the event listener with it) and the new button created. So you need to re-attach the event to the new button.
That said: why does the button have to be inside the div? The mind boggles. You can always update the button text from javascript, there's no need to replace it and keep creating new listener objects.