on click not working as expected on dynamically created elements jQuery - javascript

I have a tag when clicked alerts the data-value of the tag. It works fine , but doesn't works when i click on dynamically created elements.
<img id="no_p_fav" src="http://localhost:8000/icons/non_star.png">
Below is how i create dynamic elements
$('.all_candidate_bar').prepend('<div id = "icons"> <a class = "favorite" data-value = "'+data.msg.id+'" > <img id = "no_p_fav" src="{{url("/icons/non_star.png")}}" ></img></a></div>');
Below function doesn't work on dynamically created elements but works fine on elements which were there when the page was loaded.
$(document).ready(function(){
$('.favorite').on('click',function(){
var candidate_id = $(this).data('value');
alert(candidate_id);
});
});
I have also tried this
$('#icons').on('click','a.favorite',function(){//myFunction});
$('a').on('click','.favorite',function(){//myFunction});
How do i make it work for elements for both dynamic and static elements ?

Since the #icon is also created dynamically you cannot use event delegation against it, you need a higher level element that is there since the beginning, body for instance:
$('body').on('click','.favorite',function(){//myFunction});
The a also won't work, since the event is not delegated in this case, it is accessing the element itself
$('a').on('click','.favorite',function(){//myFunction}); // won't work

Try this Code:
$(document).ready(function(){
$(document).on('click','.favorite',function(){
var candidate_id = $(this).data('value');
alert(candidate_id);
});
});

For dynamically created element you need to to delegate the event
$(document).ready(function(){
$('body').on('click','.favorite',function(){
var candidate_id = $(this).data('value');
alert(candidate_id);
});
});

change your function like this way
$(function(){
$(document).on('click','.favorite',function(){
var candidate_id = $(this).data('value');
alert(candidate_id);
});

Related

click event not working jQuery

I am trying to handle the click event using jQuery
on upload success, I am creating the following using jQuery:
$("#uploadedImage").append( "<div class='img-wrap'>
<span class='deletePhoto'>×</span>
<img data-id='"+files[i]+"' src='"+asset_url+"uploads/ad_photo/"+files[i]+"'>
</div>
<span class='gap'></span>");
and for handling click event for the above created div's I have written this:
$('.img-wrap .deletePhoto').click(function() {
var id = $(this).closest('.img-wrap').find('img').data('id');
alert(id);
});
the above code is working properly and creates all div, but when I click on the deletePhoto span. no jQuery alert is showing.
Any help or suggestion would be a great help.
Thanks in advance
delegate the event and change as suggested:
$("#uploadedImage").on('click', '.deletePhoto', function() {
You have to delegate your event to the closest static parent #uploadedImage in your case which is available on the page load like the container which holds the newly appended div and image.
although $(document) and $(document.body) are always available to delegate the event.
It is better to use on() when you create new element after DOM has been loaded.
$(document).on('click', '.img-wrap .deletePhoto', function() {
});
You are creating your element dynamically that is why you would need .live()
but this method is deprecated in newer version.
if you want to use jquery 1.10 or above you need to call your actions in this way:
$(document).on('click','element',function(){
`your code goes in here`
})
try this:
$(".img-wrap .deletePhoto").on('click', function() {
});
You can change a little in your code.
$(".deletePhoto").off("click").on("click",function(){
//Your Code here
});
First check in debugging mode that you get length when your code is going to bind click event and another thing bind event must written after that element is appended.
And Also check css of your element (height and width) on which you are clicking and yes
$(document).on('click','Your Element',function(){
//your code goes in here
});
Will works fine
use delegate:
$('#uploadedImage').on('click','.img-wrap .deletePhoto',function() {
var id = $(this).closest('.img-wrap').find('img').data('id');
alert(id);
});
see details delegate and .on here

Not fully working jQuery script which changes div content

so my problem is here:
http://jsfiddle.net/hskhu/
When i click "Rejestracja" Link, it changes content of div, but after this when i try to click "logowanie" link nothing matters, i dont know why can someone help me? all divs with contents of Rejestracja and logowanie are under html with display:none atribute
JS here:
<script>
$(document).ready(function(){
$('#change').click(function(){
var $which = $(this).html();
var $wyjmij = $('#' + $which).html();
$('#loginbox').html($wyjmij);
});
});
</script>
You are binding an event to the element with the id #change. You are replacing the element when the link is clicked, meaning the current bound event has no valid target.
You need to bind the event to a closer static element and delegate the event to the #change.
You can do this using on().
Check the section on Direct and delegated events in the on() documentation.
Change your code to the following:
$(document).ready(function(){
$("#loginbox").on("click", "#change", function(){
var $which = $(this).html();
var $wyjmij = $('#' + $which).html();
$('#loginbox').html($wyjmij);
});
});
DEMO - Using dynamic bindings by binding to #loginbox targeting #change

jquery or js code to obtain exact node data for currently selected form item/text/image in a web page

I want to obtain the exact details for the item on a web page that has been clicked on, using jquery.
That item can be a form item (like a checkbox, text box, text area etc) or section of text (in a paragraph or div or other) or list or image ...
What I figured out is the following--
$(function(){
$('*')
.bind('click', function(event) {
//now obtain details of item that has been clicked on...
});
});
Now, I want the exact details- viz the div id/form id/paragraph #, ie all details for that particular item. How do i get this data? I understand that this data is available in the DOM but I just dont know how to get it in this particular case...
Probably the best way to do to use the target property of the event. By default, this returns a non-jQuery object, which isn't particularly useful, however wrapping it in $() solves this issue:
$(function() {
$(document).bind('click', function(event) {
var element = $(event.target);
alert(element.height()); // Get height
alert(element.attr('id')); // Get ID attribute
// ...
});
});
If you want to fix your current method, inside your click() handler, you can access the properties of that element using .attr(), and friends:
$(function() {
$('*').bind('click', function(event) {
alert($(this).height()); // Get height
alert($(this).attr('id')); // Get ID attribute
// ...
});
});
$(this) in the scope of the function references the element that was clicked. There is a list of functions that will return attributes here and here in the jQuery docs. $.attr('id') will return the element's ID, among other things, and $.data() will return data-* attributes.
To get attributes of parent elements, simply use $(this).parent(). For example, to get the ID of the form that contains the clicked element, use $(this).closest('form').attr('id');. Everything is relative to the clicked element ($(this)), so you can just use the DOM traversal functions.
However, using $('*').bind() is incredibly inefficient; you're binding an event handler to every element on the page, when really you should delegate events with .on() (jQuery 1.7+):
$(function() {
$('body').on('click', '*', function(event) {
alert($(this).height()); // Get height
alert($(this).attr('id')); // Get ID attribute
// ...
});
});
This approach only binds one event to <body> instead of an event to every element on the page.
Use the target of click event on page
$(document).click(function(event){
/* store native dom node*/
var tgt=event.target;
/* store jQuery object of dom node*/
var $tgt=$(tgt);
/* example element details*/
var details={ id : tgt.id, height: $tgt.height(), tag : tgt.tagName}
console.log( details)
})
Look at the event.target, and then you can use jQuery's .parents() method to look at every ancestor:
$(document).on('click', function(event) {
var $t = $(event.target); // the element that was actually clicked
var $p = $t.parents(); // the target's parents
var $form = $p.filter('form').first(); // the enclosing form, if it exists
});

jQuery: $(element).text() doesn't work

I am dynamically generating content - div's with links in them. Link should bring up a popup containing link's text when clicked (showMyText function). Instead I get an empty string :(
Why isn't this working? I've searched Stackoverflow and jQuery API and it should work.
function a(){
var div=document.createElement("div");
div.innerHTML='<a class="aClass" href="javascript:showMyText(this)">Link Text</a>';
var parent_div=document.getElementById('dinamicni_div');
parent_div.appendChild(div);
}
function showMyText(link){
var txt=$(link).text();
alert(txt);
}
If you're using jQuery to get the text() why not use it for everything else too?
function a() {
var $div = $("<div></div>");
var $a = $("<a></a>")
.attr("href", "#")
.addClass("aClass")
.text("Link text")
.appendTo($div);
$div.appendTo("#dinamicni_div");
}
$("#dinamicni_div").on('click', '.aClass', function() {
alert($(this).text());
});
Example fiddle
Change your code to:
div.innerHTML='<a class="aClass" onclick="showMyText(this)">Link Text</a>';
jsFiddle example.
I would take a slightly different approach and use the "live" method which will allow you to bind a click event to the dynamically created element once it is inserted into the DOM
$(document).ready(function(){
$('#dinamicni_div').html('<a class="aClass" href="#">Link Text</a>');
$(".aClass").live('click',function(){
alert($(this).text());
});
});
I find that text() stops working after the user manually edits the text area. val() continues to work as expected.

jquery.Event of dynamic elements

my code and my problem is:
<script type="text/javascript">
$(document).ready(function() {
// this variable is used to set the dynamic elements
tagFlag = '';
$("#a1").click(function(event) {
event.preventDefault();
tagFlag = 'me'; // setting the element which I want to trigger later
});
$('#'+tagFlag).click(function(e) {
// do sthing here
});
});
</script>
</head>
<body>
make the element
<p id="me">some words here</p>
</body>
</html>
but.when I set the tagFlag,and click the "p" nothing is happen.BTW.there is error when tagFlag had been set nothing.So.How can I get what I want?
Thank you very much!!
Maybe you should look at the jQuery live() method that will assign event to all existing and future elements.
http://api.jquery.com/live/
There is no element wit the ID "a1". If you want the first anchor element use
$.("a:eq(0)")
instead.
If that's not it, report back please.
use a jquery object and add the clicked elements to it:
$(document).ready(function() {
$tagFlag = $("");
$("#a1").click(function(event) {
event.preventDefault();
$tagFlag.add($(this));
});
$tagFlag.click(function(e) {
// do sthing here
});
});
You can attach a .click() handler to document and check if the target of the click was the element you cared about, similar to how .live() behaves internally, like this:
$(function() {
var tagFlag = '';
$("#a1").click(function(event) {
event.preventDefault();
tagFlag = 'me';
});
$(document).click(function(e) {
if(tagFlag && //is it even set?
(e.target.id == tagFlag || $(e.target).closest('#'+tagFlag).length)) {
//do work here
}
});
});
You can give it a try here, the only change to your markup is the addition of a child element (to show click bubbling/handling working) and giving the anchor that a1 ID I think you intended for it to have in the question.
Alternatively if you know the set of elements that may be clicked, give them a class and bind a handler to them, checking the ID like I have above...or unbind the class and rebind to the specific ID each time, there's a few ways to go about this :)

Categories