I have a bunch of images that people can click on a heart on top to "love" or "unlove". I figured out how to make it work with Ajax / jQuery but for some reason, it only works once.
The image underneath has a link to it, too ...so I need to do a preventDefault on the heart div overlayed on top. Which again, works once.
The structure is like:
<a href="...">
<div class="image">
<img src="...">
<div class="love-response love"></div>
</div>
</a>
So if they click the heart, it works correctly ...but if they click it again, it then goes to the link of the image underneath. If they however reload the page after clicking the link, they can again click it and it works to unlove it. But then again, if they click again without reloading it goes to the image underneath again.
I think it has to do with the fact that the json data is returned and then updates the content, but on further clicks it somehow doesn't do a preventDefault anymore.
What could be wrong here?
jQuery(document).ready(function($){
$('.love').click(function (e) {
e.preventDefault();
var id = $(this).data("id");
$("#love-response-" + id).hide();
$("#love-waiting-" + id).show();
$.ajax({
url: "https://www.domain.com/love.php?id=" + id,
type: "GET",
dataType: 'json',
success: function(json) {
if(json.valid == 1) {
$("#love-waiting-" + id).hide();
$("#love-response-" + id).replaceWith(json.message);
$("#love-response-" + id).show();
}
else {
$("#love-waiting-" + id).hide();
$("#love-response-" + id).replaceWith(json.message);
$("#love-response-" + id).show();
}
},
error: function (xhr, ajaxOptions, thrownError) {
$("#love-waiting-" + id).hide();
$("#love-response-" + id).html('ERROR');
},
timeout: 15000
});
});
});
The json is pretty basic. It's either:
{
"valid":"0",
"message":"<div class=\"love-response love\" id=\"love-response-782\" data-id=\"782\"><span class=\"icon love-black\"><\/span><\/div>"
}
or
{
"valid":"1",
"message":"<div class=\"love-response love\" id=\"love-response-782\" data-id=\"782\"><span class=\"icon love-red\"><\/span><\/div>"
}
I really feel like the problem is somehow with the preventDefault not executing anymore after it received the response back from json.
delegate the click event handler to sth. thats always in your DOM
as the .love is manipulated dom (loaded via ajax) so it triggers only once because the element was not there when the script was executed
simply change
$('.love').click(function (e) {
to
$(document).on('click','.love',function (e) {
When you do this:
$('.love').click(function (e) {
You're attaching that function to the click event of those matched elements. Not to the selector, but to the elements which are selected at that time. Then when you do this:
$("#love-response-" + id).replaceWith(json.message);
You remove those elements and add new ones. Those new ones don't have click events associated with them. The old ones did.
You can correct this by using event delegation. What this means is binding to the click event of some common parent element and filtering the origin of the click based on some selector. At its simplest, it would look like this:
$(document).on('click', '.love', function (e) {
// your code
});
Related
I'm trying to figure out how to change behaviour of a button using AJAX.
When the button is clicked, it means that user confirmed order recently created. AJAX calls /confirm-order/<id> and if the order has been confirmed, I want to change the button to redirect to /my-orders/ after next click on it. The problem is that it calls again the same JQuery function. I've tried already to remove class="confirm-button" attribute to avoid JQuery again but it does not work. What should I do?
It would be enough, if the button has been removed and replaced by text "Confirmed", but this.html() changes only inner html which is a text of the button.
$(document).ready(function () {
$(".confirm-button").click(function (b) {
b.preventDefault();
var $this = $(this);
var id = this.value;
var url = '/confirm-order/'+id;
$.ajax({
type: 'get',
url: url,
success: function (data) {
$this.empty();
$this.attr('href','/my-orders/');
$this.parent().attr("action", "/my-orders/");
$this.html('Confirmed');
}
})
});
});
The event handler will be still attached to the button, so this will run again:
b.preventDefault();
which will prevent the default, which is opening the href. You need to remove the event handler on success. You use the jQuery #off() method:
$(".confirm-button").off('click');
or more shortly:
$this.off('click');
You can add to your success function something like: $this.data('isConfirmed', true);
And then in your click handler start by checking for it. If it's true, redirect the user to the next page.
$(".confirm-button").click(function (b) {
b.preventDefault();
var $this = $(this);
if ($this.data('isConfirmed')) {
... redirect code ...
}
else {
... your regular code ...
}
}
You need to use .on() rather than .click() to catch events after the document is ready, because the "new" button appears later.
See http://api.jquery.com/on/
$(document).ready(function() {
$('.js-confirm').click(function(){
alert('Confirmed!');
$(this).off('click').removeClass('js-confirm').addClass('js-redirect').html('Redirect');
});
$(document).on('click', '.js-redirect', function(){
alert('Redirecting');
});
});
<button class="js-confirm">Confirm</button>
Well my main problem is the button. I can't seem to find the reason why the button doesn't show up when I already clicked a certain tr
Here is the code that displays the returned employee data from the database
$.each(data, function(index, val) {
$("#employee_list").append('<tr class="emp_delete" id="'+val.emp_id+'"><td>'+val.emp_id+'</td><td>'+val.last_name+'</td><td>'+val.first_name+
'</td><td>'+val.middle_in+'</td>'+
'<td><input type="button" value="Resigned Employee" class="deleteBtn" id="delete_"'+val.emp_id+'"></td></tr>');
});
and here is the code that shows the button if .emp_delete is clicked. then the .deleteBtn code to delete the certain data
$(".emp_delete").click(function(){
var ID=$(this).attr('id');
$("#delete_"+ID).show();
});
$(".deleteBtn").click(function(){
var ID=$(".emp_delete").attr('id');
if (confirm("Are you sure you want to delete?")) {
var dataString = 'emp_id='+ID;
$.ajax({
type: "POST",
url: "<?php echo site_url('c_employee/delete_employee'); ?>",
data: dataString,
cache: false,
success: function(html){
location.reload();
}
});
}
UPDATE
The code that #Satpal gave worked but the .deleteBtn still doesn't show up after going through the each loop.
Here is the updated code:
$('#employee_list').delegate( ".emp_delete", 'click', function() {
var ID=$(this).attr('id');
$("#delete_"+ID).show();
});
$(".deleteBtn").click(function(){
var ID=$(".emp_delete").attr('id');
if (confirm("Are you sure you want to delete?")) {
var dataString = 'emp_id='+ID;
$.ajax({
type: "POST",
url: "<?php echo site_url('c_employee/delete_employee'); ?>",
data: dataString,
cache: false,
success: function(html){
location.reload();
}
});
}
else
return false;
});
As you are adding HTML dynamically.
You need to use Event Delegation. You have to use .on() using delegated-events approach.
Use
$(document).on(event, selector, eventHandler);
In above example, document should be replaced with closest static container.
In Your case
$('#employee_list').on('click', ".emp_delete", function() {
var ID=$(this).attr('id');
$("#delete_"+ID).show();
});
Similarly you have to delegate event for ".deleteBtn"
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
EDIT
As per comment.
Since you are using jQuery 1.5, use .delegate()
$(elements).delegate( selector, events, data, handler );
In Your case
$('#employee_list').delegate( ".emp_delete", 'click', function() {
var ID=$(this).attr('id');
$("#delete_"+ID).show();
});
EDIT 2
Use similar syntax for delete button also
$('#employee_list').delegate( ".deleteBtn", 'click', function() {
});
You mean the button does not fire?
If so, that is because you define the function before you insert the element in the DOM, you need to bind it.
So instead of:
$(".deleteBtn").click(function(){
Put:
$("#employee_list").on("click",".deleteBtn",function(){
Once the document has been fully loaded, each time you add a new object to the DOM dynamically (like adding a new table row with buttons) you'll need to bind the generated element to an event or action, you cannot say "do something when someone clicks any button" you'd say "do something when someone clicks THIS button" meaning that you have to have the object created first in order to "attach" some action to it.
So let's say that you have these:
<button class="action-button" id="1">Button 1</button>
<button class="action-button" id="2">Button 2</button>
And then this javascript:
$(document).ready(function(){
$(".action-button").click(function(){
alert('My id is ' + $(this).attr('id'));
});
});
And then you later decide to add a button with some action on your js/html:
<button class="action-button" id="3">Button 3</button>
Surprise! If you click button 3 you'll get no alert...? Why, because the function that you set up for click event on document.ready parsed only the initial two buttons that existed at that moment, but since you added a third one dynamically later, the document.ready code wasn't aware of it.
So as Emil pointed out, each time you create a new element you'll want to bind it, in our example, for our button 3:
$('#3').bind('click', function(){
alert('My id is ' + $(this).attr('id'));
});
Or by the class, which is not adequate cause it would rebind existing elements and you lose performance:
$('.action-button').bind('click', function(){
alert('My id is ' + $(this).attr('id'));
});
So make sure that if you add elements that do actions or call functions you bind them when you add them, ideally, have a separate function which does whatever the button needs to do and then when you bind the new element, bind it to that function instead of putting a direct callback.
Try jquery version less than 1.9:
$('selector').live('click', function(){
});
you have a problem with the id delete
<div id="di"></div>
Algo
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
$('#algo').click(function(){
var a = 1;
//THIS IS IMPORTANT , SEE ID = "delete_" <- has a problem
$('#di').html('<td><input type="button" value="Resigned Employee" class="deleteBtn" id="delete_'+a+'"></td></tr>');
});
</script>
Is id="delete_'+val.emp_id+'" and not id="delete_"'+val.emp_id+'" (" <- error)
I have some 'static' HTML on my page:
<div id="DIVISIONS">
<ul class="nav nav-tabs" id="DIVISIONTABS">
#* <li> nodes will be injected here by javascript *#
</ul>
<div class="tab-content" id="DIVISIONTABPANES">
#* <div class="tab-pane"> nodes will be injected here by javascript *#
</div>
</div>
On page load, I create a tab 'framework', i.e. create the bootstrap tabs and tab content containers.
I trigger the process with:
$(window).bind("load", prepareDivisionTabs);
And "prepareDivisionTabs" does this:
function prepareDivisionTabs() {
// Retrieve basic data for creating tabs
$.ajax({
url: "#Url.Action("GetDivisionDataJson", "League")",
cache: false
}).done(function (data) {
var $tabs = $('#DIVISIONTABS').empty();
var $panes = $('#DIVISIONTABPANES').empty();
for (var i = 0; i < data.length; i++) {
var d = data[i];
$tabs.append("<li>" + NMWhtmlEncode(d.Name) + "</li>");
$panes.append("<div id=\"TABPANE" + d.DivisionId + "\" class=\"tab-pane\"></div>")
}
renderDivisionTabPaneContents(data);
}).fail(function (err) {
alert("AJAX error in request: " + JSON.stringify(err, null, 2));
});
}
For info, the "renderDivisionTabPaneContents" in the above does this:
function renderDivisionTabPaneContents(data) {
for (var i = 0; i < data.length; i++) {
var d = data[i];
renderDivisionTabPaneContent(d.DivisionId);
}
}
function renderDivisionTabPaneContent(id) {
var $tabPane = $('#TABPANE' + id);
$tabPane.addClass("loader")
$.ajax({
url: "/League/GetDivisionPartialView?divisionId=" + id,
cache: false
}).done(function (html) {
$tabPane.html(html);
}).fail(function (err) {
alert("AJAX error in request: " + JSON.stringify(err, null, 2));
}).always(function () {
$tabPane.removeClass("loader")
});
}
All good so far. My page loads, my tab contents are rendered, and when I click the different tabs, the relevant content is shown.
Now, rather than loading all content at the start, I want to load tab content just-in-time by using the 'shown' event of the tabs. To test this, I've wanted to just make sure I could get a javascript alert when the tab was shown. So, I create the following to trigger the attachment of tab shown events:
$(function () {
attachTabShownEvents();
})
which calls:
function attachTabShownEvents() {
$(document).on('shown', 'a[data-toggle="tab"]', function (e) {
alert('TAB CHANGED');
})
}
I'd therefore expect so see the "TAB CHANGED" alert after the change of tab. But ... I see no alerts.
Could anybody help me out here?
The correct event binding for tab change is shown.bs.tab.
$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
alert('TAB CHANGED');
})
Update 11-01-2020 --- Bootstrap 4.5
This is still the correct answer however, this is a bit of additional helpful information found all the way at the bottom of the official bootstrap docs page at: https://getbootstrap.com/docs/4.5/components/navs/#tabs
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
e.target // newly activated tab
e.relatedTarget // previous active tab
})
You can determine which tab has been selected each time the code fires with e.target.
If you have unique IDs on your elements then you could do something like the following so code only runs when the appropriate tab is clicked.
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
switch (e.target.id){
case "mainTab":{
doMainTabStuff();
break;
}
case "configTab":{
doConfigTabStuff();
break;
}
}
})
<a data-toggle="tab" href="#some_special_tab_anchor">
<div id="some_special_tab_anchor" class="tab-pane fade">
special tab content
</div>
$( 'a[data-toggle="tab"]' ).on( 'shown.bs.tab', function( evt ) {
var anchor = $( evt.target ).attr( 'href' );
alert("TAB SHOWN = "+anchor);
// take action based on what tab was shown
if(anchor === "some_special_tab_anchor"){
// do my special thing :)
}
});
Use my Nuget package for lazyloading bootstrap tabs here, its very simple,
just add "lazyload" class to the "ul" element of bootstrap tabs, then add "data-url" equal to url to load to the any tabs anchor element (a). thats it.
https://www.nuget.org/packages/MT.BootstrapTabsLazyLoader.js/
'show' and 'shown' events didn't work for me. My solution is not exactly specifically OP's situation, but the general concepts are there.
I had the same issue with bootstrap forcing its own onclick events
on tabs (menu buttons and content panels). I wanted to lazy load stuff into a panel depending on what menu button was clicked, and some buttons show a panel on the current page, others were to load a page into an iframe.
At first, I stuffed data into a hidden form field tag, which was the same issue. The trick is to detect some sort of change and act on that. I solved the problem by forcing a change and using an alternate event listening on the buttons without having to touch bootstrap.
1) stash iframe target in button as data attribute:
$('#btn_for_iframe').attr('data-url',iframeurl);
2) bind alternate event onto fire off thingy,
and inside, swap out the iframe source
$('#btn_for_iframe').on('mouseup',function(){
console.log(this+' was activated');
$('#iframe').attr('src',$('#btn_for_iframe').attr('data-url'));
});
3) force 'change' event on panel shows, then load iframe src
$('#iframe_panel_wrapper').show().trigger('change');
or you can put the change trigger in the mouseup above.
$(document).ready(function(){
$(".nav-tabs a").click(function(){
$(this).tab('show');
});
$('.nav-tabs a').on('shown.bs.tab', function(event){
alert('tab shown');
});
});
I've made a site that displays a user's Facebook photos. The code below appends the photos to the div "facebook-images". This part works fine. The problem I have is that the images are being appended after the Javascript code below is loaded; so the handler "fb-image" is not created when the browser reads the click function code at the bottom, therefore it does not work.
I believe I need to use jQuery on(), but where? I've tried to put on() everywhere in the code below. I've tried to bind with append, I've tried live (which I know is deprecated but worth a shot). Nothing is working.
Any ideas?
<div class="target">
</div>
<div id="facebook-images">
</div>
<script>
$.when(window.deferredes.fbLoaded, window.deferredes.fbLoggedIn).then(function () {
$.getJSON('https://graph.facebook.com/me/photos?access_token=' + FB.getAccessToken(), function (data) {
$.each(data.data, function (i, face) {
$('#facebook-images').append("<div class='fb-image'><img src='" + face.source + "' ></div>");
});
});
});
$(".fb-image img").click(function () {
$(".target").append("<h1>hi</h1>");
});
</script>
The simplest way to fix this is to add the click handlers AFTER the images are inserted into the page.
<script>
$.when(window.deferredes.fbLoaded, window.deferredes.fbLoggedIn).then(function () {
$.getJSON('https://graph.facebook.com/me/photos?access_token=' + FB.getAccessToken(), function (data) {
$.each(data.data, function (i, face) {
$('#facebook-images').append("<div class='fb-image'><img src='" + face.source + "' ></div>");
});
$(".fb-image img").click(function () {
$(".target").append("<h1>hi</h1>");
});
});
});
</script>
You can also use delegated event handling if you want. To do that, you set the event handler on a common parent that does exist at the time you run the event handling code with .on() and you use the delegated form of .on() by passing it a selector like this:
<script>
$.when(window.deferredes.fbLoaded, window.deferredes.fbLoggedIn).then(function () {
$.getJSON('https://graph.facebook.com/me/photos?access_token=' + FB.getAccessToken(), function (data) {
$.each(data.data, function (i, face) {
$('#facebook-images').append("<div class='fb-image'><img src='" + face.source + "' ></div>");
});
});
});
$("#facebook-images").on('click', ".fb-image img", function () {
$(".target").append("<h1>hi</h1>");
});
</script>
The delegated form of .on() works like this:
$(selector of static parent).on(event, selector that matches dynamic object, fn);
I have the following mouseover function:
$('.msg_id').live("mouseover", function() {
$(this).css('cursor', 'pointer');
tid = $(this).attr('id');
idx = $(this).attr('name');
resp="";
$.ajax({
async: false,
url: "log_msg.asp",
data: $("#msgForm").serialize() + "&aktion=popup&msg_id="+tid+"&msg_id"+idx,
success: function(data){
$("#"+tid).html(data);
}
});
//$.post("log_msg.asp", $("#msgForm").serialize() + "&aktion=popup&msg_id="+tid+"&msg_id"+idx,
//function(data) {
//}).success(function(){
//$("#"+tid).html(data);
//resp=data;
//$('#bub'+tid).css('display', 'block');
//popd.css('display', 'block');
//});
});
It puts some html code inside .msg_id ( $("#"+tid).html(data); ).
The function mouseover is called in a loop. The ajax request is sent all the time while mouseovering it, not only once.
How can I fix it?
I have also tried mouseenter, but it fires in a loop too.
You might want to use the mouseenter() event instead, as mouseover will fire upon every move inside the element.
$('.msg_id').live("mouseenter", function() {
//Do work here
});
or if live isn't required, simply:
$('.msg_id').mouseenter(function() {
//Do work here
});
MouseOver():
Will fire upon entering an element can fire inside of any child elements.
MouseEnter():
Will fire upon entering an element, and only that element.
You want to use mouseenter