I have a page called forms.php with a javascript included in its head and a div called fadeinContents
i used Ajax to load part of a file called #sections1 into this div which works quite well
But i need to execute some Jquery on the loaded contents in the fadeinContents when they are clicked. Ive read other post but couldn't understand them well..
Here are my files
forms.php
<html>
<head>
<script type="text/javascript" src="scripts/scripts.js"></script>
<script type="text/javascript" src="scripts/login.js"></script>
</head>
<body>
<div class="login_link">login</div>
<div class="signup_link">signup</div>
<div class="fadeinContents">
<!--Loaded contents goes here -->
</div>
</html>
Here's my Jquery
$(document).ready(function(e) {
$('#fadeinContents').load('forms.php #sections1');
$('.login_link').click(function(e) {
$('#fadeinContents').load('forms.php #sections1');
});
$('.signup_link').click(function(e) {
$('#fadeinContents').load('forms.php #sections2');
});
$('.recoverPassword').click(function(e) {
$('#fadeinContents').load('forms.php #sections3');
});
});
Loaded File containing
<div class="sections1">
<div class="signup">
<!-- Signup Forms Here -->
</div>
</div>
<div class="sections2">
<div class="login">
<!-- loginForms Here -->
</div>
</div>
<div class="sections3">
<div class="recoverPassword">
<!-- recover form Here -->
</div>
</div>
My problem is that the Recover password click function is not working because it was loaded, Please how can i make this work?
thnx in advance..
then you should bind that event differently. try it like this
$('.fadeinContents').delegate('.login_link', 'click', function(e) {
$('#fadeinContents').load('forms.php #sections3');
});
and so on for the rest of them.
This means that the click event is binded on the .fadeinContents but when triggered, it checks if the target is a .login_link and if so it will triggers the given callback. So delegating the event handler to a higher node will ensure that no matter when the content of the node will load/change or how many elements you have, if they match the criteria the event handler will trigger.
Delegating events is a bit more memory efficient as well. If you have for example one hundred cells you want to add click events to, doing a $(".cell").click( will attach a event listener on every one of them. Delegating it to the body for example with $("body").delegate('.cell', 'click', will only attach one event (and then do some looping and checking there, that's true) but you'll end up with only one event listener and it won't matter how many nodes you later add or remove. they will trigger that click event
Related
I am performing that On Button Clicked a div is created but issue is that it is not performing as same as main div is performing like resizing & draggable.Please Help?
<html>
<head>
<link rel="stylesheet" href="test.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script>
$(function () {
$("#box").resizable({
alsoResize:"#main",
alsoResize:"#title_bar",
alsoResize:"#container"
});
$('#main').draggable();
$("#button").click(function () {
if ($(this).html() == "-") {
$(this).html("+");
} else {
$(this).html("-");
}
$("#box").slideToggle();
});
$("#NewWidget").click(function() {
$("#container").append('<div class="main" id="main"><div id="title_bar" ><div id="button">-</div></div><div id="box"><div><h4>Hi user</h4><p>Hello Users. How are YOU?</p> </div></div>');
});
});</script>
</head>
<body>
<input type="button" id="NewWidget" value="Add New Widget"/>
<div id="container">
<div class="main" id="main" >
<div id="title_bar" >
<div id="button">-</div>
</div>
<div id="box">
<div>
The ID's needs to be unique, so if you create a lot of elements, either make ID's unique or use classes or data-id attribute to recognize which box is which - in the example in codepen i showed you how to create ID's with simple counter variable, that is available in this scope (remember about closures).
What you did in your code is only appending a new structure to DOM, there is no event handlers/hooks attached to this element, that's why you either need to create new event handler/hooks when adding the element to the DOM, or after, in my example, i will to it before adding the element to the DOM.
Here's link to codepen:
https://codepen.io/anon/pen/GEyPXr
Additional hint: whenever possible, avoid creating anonymous function, always either name them, or reffer to them, meaning:
$(".main").find('.button').on('click',function(){
// this looks weak, plus anonymous function doesn't tell you what it does
});
use this instead:
$(".main").find('.button').on('click',makeButtonWork);
function makeButtonWork(){
//this looks much better, plus you named the function and you know the purspose of it, without looking through code
}
To respond to comments:
changing starting position of given element can be done by adding:
$('#main-' + counter).css({'top': 100, 'left' : 20}) //your positions here
in the makeButtonWork
see updated codepen for more info
Javascript events don't work this way. Take it as that in the moment when you call $('#main').draggable();, then browser finds matching element (here the one with ID 'main') and does some action with it (here enables the draggable functionality).
If you later add another element, which would also have been matching, it doesn't mean anything - it is just a plain div, until you call some script again.
Also, keep in mind that ID's must be unique on your page, you can't have two id="main" divs on same page. Use classes instead.
$("#NewWidget").click(function() {
var $newElement = $('<div class="main"><div class="title_bar" ><div class="button">-</div></div><div class="box"><div><h4>Hi user</h4><p>Hello Users. How are YOU?</p> </div></div>');
$newElement.find('.main').draggable();
$newElement.find('.button').click( /* add the click handler function here */ );
$newElement.find('.box').resizable( /* resizable params goes here */ );
$("#container").append($newElement);
});
hello I'm having trouble using level 2 DOM to handle events, i've looked around but just don't quite understand how it works, and allways end up doing simple code like:
<element onClick = " some code" > </element>
instead of reaching the element from outside of html code, please help, I know this is an easy topic but just can't make it work...
there is also some css code but its not relevant to my question so here's my code:
<script type="text/javascript">
function rotate( xy , deegrees){
document.getElementById("cube").style.WebkitTransform = " rotate"+xy+"("+deegrees+"deg)";
}
// so this is where its supposed to be but not working
// whats wrong ?
document.getElementById("upp").addEventListener("click", rotate('X', 540), true);
myFunction();
</script>
</head>
<body>
document.getElementById('cube').style.WebkitTransform = 'rotateX(90deg)';
<div id="button_container">
<button id="upp" onMouseOver=" rotate('X',90); "> UP</button>
<button id="downn" onMouseOver = " rotate('X',-90); "> DOWN</button>
<button id="leftt" onMouseOver = " rotate('Y',00); "> LEFT</button>
<button id="rightt" onMouseOver = " rotate('Y',-90); "> RIGHT</button>
</div>
<section class="container">
<div id="cube">
<figure class="front">front</figure>
<figure class="back">back</figure>
<figure class="right">right</figure>
<figure class="left">left</figure>
<figure class="top">top</figure>
<figure class="bottom">bottom</figure>
</div>
</section>
This is a function call:
rotate('X', 540)
It's a function call no matter where it appears, like when you call addEventListener:
document.getElementById("upp").addEventListener("click", rotate('X', 540), true);
Thus, you're passing the result of calling your "rotate" function instead of the function itself:
document.getElementById("upp").addEventListener("click", function() { rotate('X', 540) }, true);
By wrapping the function call in another function, you correctly supply addEventListener() with an event handler to be called when the "click" happens.
In addition to that, you're trying to add the event handler in a script block that appears before the DOM element you're trying to affect. When the script runs, there won't be an element in the DOM with the id you're looking for. Either wrap your event handler setup in a "load" event handler, or move the script block to the end of the <body>.
Your code likely is running before your DOM is applied. Move script tag to bottom of page or use onload function to execute your code after the DOM has completed its load phase.
http://api.jquery.com/ready/
Validate this by ensuring you can log a element you are attempting to get a reference to...
console.log(document.getElementById("upp"));
Should return a DOM element.
I have a simple share button aside every post, I'm using .toggle() function to show and hide the options. The code looks something like this:
<div id="posts">
<div class="post">
<div class="content">
Post content
</div>
<div class="share">
<div class="trigger"> Share </div>
<div class="hidden"> Share on Facebook </div>
<div class="hidden"> Share on Twitter </div>
</div>
</div><!-- each post -->
<div id="new">
</div><!-- new post container -->
</div><!-- Posts -->
<script>
function shareThis(){
$('.trigger').click(function(){
$(this).siblings().toggle();
});
}
$(document).ready(function(){
shareThis();
$('#new').load("/post2", function(){
shareThis();
});
});
</script>
I call this function once when the page loads, and then every time a new post is loaded.
The problem is, it works in the first time when the page is loaded, and just works for the new element when a new post is loaded. I also tried this with 'each' function but same result.
So it's just working for the last call, similar to these question i found here and here, and some others, but didn't get a solution for my problem there.
Thanks!
The problem is, it works in the first time when the page is loaded, and just works for the new element when a new post is loaded.
Your issue could be that you are binding the event twice (or as many number of times you load #new contents) to the existing .trigger by calling shareThis inside the load callback. So basically when you click on the old .trigger it will trigger the handler twice, i.e toggling it twice which keeps them in the same state. SO either bind the event to the newly added ones alone or turn the click event off and turn it on in the function shareThis:
function shareThis(){
$('.trigger').off('click').on('click', function(){
$(this).siblings().toggle();
});
}
You could also try:
function shareThis(ctx){
ctx = ctx || document;
$('.trigger', ctx).click(function(){
$(this).siblings().toggle();
});
}
$(document).ready(function(){
shareThis();
$('#new').load("/post2", function(){
shareThis(this);
});
});
Try binding the click to the document instead. Only need to do it once :)
$(document).on('click', '.trigger', function () {
$(this).siblings().toggle();
}).ready(function () {
$('#new').load("/post2");
});
http://api.jquery.com/on/
http://training.bocoup.com/screencasts/more-efficient-event-handlers/
This question already has answers here:
Event handler not working on dynamic content [duplicate]
(2 answers)
Events triggered by dynamically generated element are not captured by event handler
(5 answers)
Closed 9 years ago.
I have a <select class="listenToMe" /> that when changes does something. I also have a separate link that when clicked performs an ajax request and returns more dom elements and inside them it has another <select class="listenToMe" />
I would like my event listener to be applied to this element as well. I am trying to use jQuery's on method but it doesn't appear to be working:
JS
var selectListener = function() { alert('you change me!'};
$('.listenToMe').on("change", selectListener);
$('.addMore').click( function() {
$.post('myWebPage.php', {} , (function(data) {
$(this).before(data);
// data is something like <div><select class="listenToMe" /></div>
}).bind(this));
});
HTML
<div>
<div>
<select class="listenToMe" />
</div>
<div>
<select class="listenToMe" />
</div>
<a class="addMore">Click me</a>
</div>
Any suggestions?
You can try
$(document).on('change', '.listenToMe', function(){
// Your code here
})
Your using on like live. The difference is subtle but important. You attach on to a static element in your markup and then filter the event based on a selector. This way the on event never goes out of scope, e.g. if I have the markup
<!-- this div is not dynamically loaded-->
<div id="mystaticDiv">
<!--insert dynamic content here-->
</div>
which when I add my dynamic markup will become:
<!-- this div is not dynamically loaded-->
<div id="mystaticDiv">
<!--insert dynamic content here-->
<div class="myDynamicdiv></div>
</div>
To fire an event on the click of my dynamic div that never needs rebinding I would write the following jQuery:
$('#mystaticDiv').on('click', '.myDynamicdiv', function() {/*Do stuff*/});
So I'm binding my on to the #mystaticDiv but filtering on .myDynamicdiv. Now I can add as many .myDynamicdivs as I want and this will work.
I mentioned live. This is deprecated but works in the same way as you were attempting. This attaches an event to the document of the page with a selector base on the selector your attaching live to. So $('.myDynamicdiv').live('click', function() {/*Do stuff*/}); is directly equivalent to $(document).on('click', '.myDynamicdiv', function() {/*Do stuff*/});. the reason I mention this is this is how you were trying to use on.
Your code $('.listenToMe').on("change", selectListener);. Will not work for dynamic content. This code attaches the event to the dynamic content, that doesn't exist yet. So the is never actually bound. Interestingly $('.listenToMe').on("change", selectListener); is exactly what $('.listenToMe').change(selectListener); does under the hood.
Here's my issue.
I have a javascript function that update a div when i click the proper link. And it is working.
Since i have cliked the link my div content is updated with another Javascript. This time to close it.
Its fairly simple but i cant get it to work and i dont know why!
Here is the code that is in the page when it load for the first time
The div id config_window
<div id="config_window" class="config_window">
<div id="conception" class="conception">Conception et design graphique Zéro Gravité.
</div>
<div id="admin_btn"class="admin_btn">administration.</div>
<div id="test">test</div>
</div>
Now the Javascript that call for the update inside that div
<script language="javascript" type="text/javascript">
$("#admin_btn").click(
function(){
$('#config_window').addClass('config_open');
config_set('config_window','open','var')
}
);
</script>
So far it's working my div is getting updated and i see the new content. The new content is
<div id="conception" class="conception">Conception et design graphique Zéro Gravité.
</div>
<div id="admin_btn_x" class="admin_btn">Terminer.</div>
<script language="javascript" type="text/javascript">
$("#admin_btn_x").click(
function(){
$('#config_window').removeClass('config_open');
config_set('config_window','close','var')
}
);
</script>
i was expecting that same function to work but its not!! and i dont get why since the first one is.
Could it be becuse my second script is in the div that get updated??
Thanks!
I suspect it's because the element that the second handler is supposed to apply to doesn't exist until after the DIV is updated and the function applying the handler is executed before the DIV is updated -- therefore the handler is not applied. You might want to try using the live handlers for the click event so that it will apply to all elements matching the selector no matter when the element is added. You can add both handlers on page load and they will apply to the elements with those ids whether they are added dynamically or not.
<script type="text/javascript">
$("#admin_btn").live('click', function(){
$('#config_window').addClass('config_open');
config_set('config_window','open','var')
});
);
$('#admin_btn_x').live('click', function() {
$('#config_window').removeClass('config_open');
config_set('config_window','close','var')
});
</script>
Is there a reason you add divide the function into two scripts? I would change your script to something like this:
<script type="text/javascript">
$(document).ready(function() {
$('#config_window').hide(); // just in case
$('#admin_btn').bind("click", function() {
if($('#config_window').is(':hidden')){
$('#config_window').show();
config_set('config_window','open','var')
} else {
$('#config_window').hide();
config_set('config_window','close','var')
}
});
});
</script>