Not fully working jQuery script which changes div content - javascript

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

Related

dynamic <a></a> doesn't run with jquery

I want to make a web site for a photos.
Inside a dynamic div created with a jquery function (.append) there is this anchor:
<a href='#' style='color:green;' id='"+this.foto_id+"' data-id='"+this.foto_id+"' class='modificaDataFoto modificaDataFoto"+this.foto_id+"'>Modifica</a>
The page is load normally and if I use the browser debugger I see all the HTML code including all dynamic data from database...
But if I try to set a class of the anchor in a jquery function it doesn't run:
$('.modificaDataFoto').bind('click', function(event) {
event.preventDefault();
var idFotoModifica= $(this).attr("data-id");
console.log(idFotoModifica);
$("dataFoto"+idFotoModifica).focus();
$("dataFoto"+idFotoModifica).css("color", "red");
$(this).attr("class", "modificaDataFotoConferma");
});
Why does that function not work?
.bind() only works on elements that are already present in the DOM. It's likely that you're trying to bind the click event to the element before the dynamic element exists.
There are two ways to fix this:
wait until after the <a> element has been appended to the document before running your $('.modificaDataFoto').bind(), or
Delegate the click event from a non-dynamic element (or the document itself):
$(document).on('click', '.modificaDataFoto', function() {
// this is essentially the same as your existing function; I've
// consolidated it a bit and removed the no-longer-needed preventDefault.
$("dataFoto" + $(this).attr("data-id")).css("color", "red").focus();
$(this).attr("class", "modificaDataFotoConferma");
}
Use this code:
$(document).on('click', '.modificaDataFoto', function(event) {
event.preventDefault();
var idFotoModifica = $(this).attr("data-id");
console.log(idFotoModifica);
$("dataFoto"+idFotoModifica).focus();
$("dataFoto"+idFotoModifica).css("color", "red");
$(this).attr("class", "modificaDataFotoConferma");
});
I'm not entirely sure if I understood your question but if you are trying to change the element's class name then you can simply do this:
$( this ).switchClass( "old class", "modificaDataFotoConferma", 1000, "easeInOutQuad" );
instead of
$(this).attr("class", "modificaDataFotoConferma");
You also have the .toggleClass()
EDIT:
You can also use removeClass() and then use the addClass().

on click not working as expected on dynamically created elements jQuery

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

Changing a child span to a link which calls a function

I have an AJAX function which populates a div with spans of data into a template. I would like to append these spans to links, which when clicked call a function. With what I do have, it does seem an href link is getting added, but the text itself is still not clickable.
Here's the html from the IDE as well as from the developer tools in IE :
<div id="subtotal_menu">
</div>
Here's what I have tried so far:
var $menu = $('#subtotal_menu');
$menu.empty();
$('#checkTemplate').tmpl(data.d.Checks).appendTo($menu);
$("#subtotal_menu").find("span").attr('href','myfunction()');
Also tried to create a separate function to operate on the DOM element:
function createVendorInvoiceLinks() {
var subTotalmenu = document.getElementById("#subtotal_menu").find("span");
var aTag = document.createElement('a');
aTag.setAttribute('href', "myfunction()");
subTotalmenu.appendChild(aTag);
}
This could help you:
var $menu = $('#subtotal_menu');
$menu.find("span").append('Link');
// append an anchor to the span inside #subtotal_menu
// set javascript:void(0) as href to avoid unwanted behaviour on click
$('#subtotal_menu').on('click', 'a',function(){
alert('clicked');
// do whatever myfunction() does
});
//set up a proper event handler and use event-delegation to cope with
//dynamic added element from e.g. your mentioned ajax-request
When you want the whole span to be clickable just change the binding from the event handler from a to span. This way you don't event need to append an anchor.
Example
Reference
jQuery .append()
event delegation
Instead of appending the <a> element to the span, you should do the opposite:
function createVendorInvoiceLinks() {
var subTotalmenu = document.getElementById("#subtotal_menu").find("span");
var aTag = document.createElement('a');
aTag.setAttribute('href', "myfunction()");
aTag.appendChild(subTotalmenu);
}
So you don't generate a <a> with no content.

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

'.on' click not running function?

I have a function that when it runs new markup is generated on the fly...
$('.search input[type="image"]').on('click', function(){
// Open directions in a map
if($('#TXT_SAddr').val() === ''){
return false;
$('.directions .search').css('background' , '#ff0000');
} else {
var from = $('#TXT_SAddr').val();
var to = $('.postal-code').html();
var directions = 'http://maps.google.com/maps?saddr=' + from + '&daddr=' + to + '&output=embed';
var modal = '<div class="apply-modal modal"><a class="close-apply-now" style="margin-bottom: 20px;"><img src="http://site.co.uk/images/closeModal.png" alt="Close" style="border-width:0px;"></a><div class="holder"><iframe src="'+directions+'" style="border:none; width:100%; height:500px;" border="0"></iframe></div></div>';
$('body').prepend('<div class="modalOverlay"/>' + modal);
$('.modal').animate({
'opacity': 1,
'top': '100px'
}, 700, 'easeOutBack');
}
return false;
});
If you can see, the above generates a div with an anchor under the class name of 'close-apply-now'.
I now want to bind a function to this and I've tried using...
$('a.close-apply-now').on('click', function(){
alert('asdasd');
});
with no luck, can anybody see where I may be going wrong? Not even my alert is working.
Since the close-apply-now div is added dynamically, you need to use event delegation to register the event handler like:
// New way (jQuery 1.7+) - .on(events, selector, handler)
$('body').on('click', 'a.close-apply-now', function(event) {
event.preventDefault();
alert('asdasd');
});
This will attach your click event to any anchors with class close-apply-now within the body element.
The syntax for event delegation is slightly different.
The event need to be bind to an element which is already existing in the dom while the target element selector needs to be passed as the second argument
$(document).on('click', 'a.close-apply-now', function(){
alert('asdasd');
});
The close-apply-now div is added dynamically. You have to add the selector parameter, otherwise the event is directly bound (doesn't work for dynamically loaded content) instead of delegated. See http://api.jquery.com/on/#direct-and-delegated-events
Change your code to
$(document.body).on('click', '.update' ,function(){
The jQuery set receives the event then delegates it to elements matching the selector given as argument. This means that contrary to when using live, the jQuery set elements must exist when you execute the code.
Use jQuery's live() method. Description: Attach an event handler for all elements which match the current selector, now and in the future.
$("a.close-apply-now").live("click", function(){
alert('asdasd');
});
Try Both in Jsfiddle

Categories