JQuery: How can I extend a script over some dynamically loaded content? - javascript

I have a little problem that I was hoping some of you could help me out with.
On clicking a button, I would like to update a div with the content of another page.
Let's say that homepage.html is like this:
<html>
<head>
<script type="text/javascript" src="JQUERY.JS"></script>
<script type="text/javascript">
$(function()
{
$(".alert").click(function()
{
alert("HELLO");
return false;
});
$(".load").click(function()
{
$("#content").load("FILE.HTML");
return false;
});
});
</script>
</head>
<body>
CLICK ME
<div id="content"></div>
</body>
</html>
A rather simple file.
Now let's say that FILE.HTML has this line only:
CLICK ME
Now what I am looking for is: when i click .alert, the alert box pops up. I don't know why it doesn't.
So my question is: why is my loaded code not affected by the script?
Thank you for your help.

You need to use the jQuery Delegate to achieve that...

The contents from file.html are not present the moment you attach the click event to the ".alert" items (actually there are no .alert items when that code runs!).
You need to use jQuery's delegate or live methods which use event bubbling in order to capture events not only from existing elements but also from new elements that are inserted in the DOM later.
This also has the nice side effect of using only one event handler instead of one for each .alert element.

You have to use $.live:
$(".alert").live('click', function()
{
alert("HELLO");
return false;
});
You don't have to wait until you add in your dynamic content, this function applies your event handler to all future elements that match your selector.

Related

JavaScript event execute immediately after bind? [duplicate]

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();

onClick eventlistener in JS without using onclick function in HTML

I have a html file and js file I want to execute JS when a button is clicked in html. for this I can use onclick event in html but the condition is that I should not modify the HTML file.
I tried to add eventlistener in my JS but that didn't worked.
<p align=center>
<button class="stdbutton" id=button2 name=button2>
Click Me
</button>
</p>
$("button2").click(function() {
alert("button2 clicked");
});
please see the fiddle link for further reference: http://jsfiddle.net/gqpr0g9w/
thanks in advance
Try the FIDDLE,
Basically the first issue with your fiddle was you are using js library other than jquery. Jquery code won't execute without referencing the jquery library.
Secondly you are using an invalid selector,
$("button2")
you can replace this with an id based selector (# selector) as per your markup
$("#button2")
And finally try wrapping the code under jquery closure under document ready event that will ensure that the event will attach when the related object is loaded on the browser.
Finally will becomes
$(document).ready(function() {
$("#button2").click(function() {
alert("button2 clicked");
});
});
Hope it works for you..
Include jQuery in your jsfiddle. Use one of the below to attach an event listener for click using jQuery
$("#button2").on("click", function() {
alert("button 2 clicked");
});
or
$("#button2").click(function() {
alert("button2 clicked");
});
case jQuery is included in the html:
js file -
$("#button2").click(function() {
alert("button2 clicked");
});
// notice the # symbol before the word "button2" representing that we are looking for an ID
case jQuery is NOT included in the html:
<script src="lib/jquery-2.1.4.min.js"></script>
<script src="js/myJavaScript.js"></script>
jQuery script must first be included
and then you can execute the same code as shown above.
Well, you are trying to use jQuery, but there is no jQuery included in your html-File. In fact there is no script included in your html at all like
<script src="lib/jquery-2.1.4.min.js"></script>
<script src="js/myJavaScript.js"></script>
I don't think you will be able to do that without modifying the html-file.

Using jQuery to change the background image

I am trying to change the background image of a link when it get clicked. I keep getting the error that you cannot call 'click' on null.
JQuery (in the header)
<script type="text/javascript">
$('a.upvote-arrow').click(function(){
$('#tempid1').css('background-image','url(../images/icons/up-arrow2.png)');
});
</script>
HTML
<div class="top-comment-vote">
</div>
Thanks
Try adding $(document).ready:
<script type="text/javascript">
$(document).ready(function(){
$('a.upvote-arrow').click(function(){
$(this).css('background-image','url(../images/icons/up-arrow2.png)');
});
})
</script>
Are you sure this script is being loaded after the html is in the DOM?
Try wrapping what you wrote in a onload closure.
$(function() {
$('a.upvote-arrow').click(function(){
$('#tempid1').css('background-image','url(../images/icons/up-arrow2.png)');
});
});
Another thing you can do is take advantage of delegation for the event registration.
$('body').on("click", ".a.upvote-arrow", function(){
$('#tempid1').css('background-image','url(../images/icons/up-arrow2.png)');
});
This binds it to the body instead.
Try wrapping your script with document.ready; I suspect that you're script might be running before your entire page loads.

How can I make entire DIV clickable AND open child links in separate DIV?

I asked a precursor to this question here:
Click link in DIV and show PHP/HTML in separate DIV
Then, after I removed the first script shown below, I was able to get the second script to work. I revised my question, but it appears to have gone silent. So I have a slightly modified question.
What is the conflict between the 2 scripts below and how can I modify them to work in tandem? Basically I want to be able to click anywhere in the DIV (".side_items") and have the child anchor links open in a separate DIV ("#main_content")
Javascript:
<script type="text/javascript">
$(document).ready(function(){
$(".side_items").click(function(){
window.location=$(this).find("a").attr("href");
return false;
})
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$(".side_items a").click(function(e){
e.preventDefault();
$("#main_content").load($(this).attr("href"));
});
});
</script>
HTML: (slightly simplified)
<div id="main_content">
</div>
<div id="right_side">
<div class="side_items">
<a href="content.html">
<img src="images/examplethumb.png" /><br />
Content</a>
</div>
</div>
Both scripts work independently to achieve their individual desired result.
This will do it:
$(document).ready(function(){
$(".side_items").click(function(){
$("#main_content").load($(this).find("a").attr("href"));
return false;
})
});
Breaking it down:
$(".side_items").click(fn);
Find all the elements with a class of side_items and assign a click event handler (fn) to them. Each time one of these elements is clicked, fn is executed with the context of the element. In the discarded code you were using the selector .side_items a, which meant the click handler was only bound to the links inside the div, not the div itself.
$(this).find("a").attr("href")
Find all the links that are contained within the current element (this), and get the value of the href attribute from the first element found. In the discarded code the context (this) was a link. Since our handler is now bound to the containing div, the context is also the div. To get the link you have to find it.
$("#main_content").load(href);
Find the element with an id of main_content and load the content found at href into it. In the discarded code you were setting location.href, which causes the page to navigate away.
I think your issue is that you're trying to assign the $().ready(..) handler twice.
Try combing scripts like this
<script type="text/javascript">
var change_location = function(){
$(".side_items").click(function(){
window.location=$(this).find("a").attr("href");
return false;
});
}
var load_location = function(){
$(".side_items a").click(function(e){
e.preventDefault();
$("#main_content").load($(this).attr("href"));
});
}
$().ready(function(){
change_location();
load_function();
});
</script>
Hope that helps

Button onclick to click() jquery

I have a button that reacts to onclick() at the moment, but I want it to work with jquery.
$('#nupp1').click(function() {
raiseButtonAction(realPlayer, gameState);
});
raisebuttonaction is in another .js
This piece of code isn't working.
Am I doing something wrong?
edit1:
$(document).ready(function() {
$('#nupp1').click(function() {
raiseButtonAction(realPlayer, gameState);
});
});
Assuming you have this:
<head>
<scripts />
</head>
<body>
<a id="nupp1"></a>
</body>
You code will not work. jQuery will not be able to find the element. The element must exists for that function to work. So
<a id="nupp1"></a>
<script />
Will work because a is being rendered before the script.
You can also use $(document).ready or $() to execute your function when the DOM nodes load.
Or you can use jQuery.live.
jQuery API
ready Specify a function to execute when the DOM is fully loaded.
live Attach a handler to the event for all elements which match the current selector, now and in the future.

Categories