So I have a jquery click function assigned to an on/off toggle. Very simple script:
$('.on-off').on('click', function(e) {
e.preventDefault();
var $this = $(this);
$this.find('.slider').toggleClass('active');
});
We have two versions of this toggle. One toggles instantly when clicked and then we submit the value when clicking next(aka submit).
Our other one calls a jquery ajax function that toggles on success and upon success if it is a specific message code that is defined on the backend.
jQuery.ajax({
url: url,
type: 'POST',
dataType: 'json',
cache: false,
data: {'requestType': requestType},
success: function(message) {
if(message.STATUS=='2000'){
if(currentButtonClicked=='dashboardChargingButton'){
if($('#dashboardChargingButton').html()==startCharge)
$('#dashboardChargingButton').html(stopCharge);
else
$('#dashboardChargingButton').html(startCharge);
}
if(currentButtonClicked=='invokeChargingButton'){
$( "#invokeChargingButton .slider" ).toggleClass( 'active');
}
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status + " - " + xhr.statusText);
}
});
}
As you can see I have to toggle the class again using the same code but with direct targeting.
The on off toggles of this type have an onclick inside the actual html calling the function that handles this ajax.
My goal is to have my first set of code the one that targets the element and toggles the class to do all of this, but dynamically to where we don't have to call a function everytime.
Conceptually what I thought is:
$('.on-off').on('click', function(e) {
e.preventDefault();
var $this = $(this);
if (!$this.attr('onclick')) {
$this.find('.slider').toggleClass('active');
} else {
var clickFunction = $this.attr('onclick');
call the clickFunction
if (clickfunction = true) {
$this.find('.slider').toggleClass('active');
}
}
});
What this would do is grab the onclick, but not call it until I specify. And inside the ajax request instead of toggling I would just return true.
This might not be the best method. I am just trying to ecapsulate everything to limit the amount of code as well as make all the dom changes for those elements in one spot for any potential defects.
Here is a link to a basic fiddle of the on/off toggle.
Fiddle
I hope I explained everything in good enough detail.
Related
i face a problem of jquery click function when i scroll down in list.
in list, data is loaded by ajax request and when i scroll down then click function (trigger) is not working.
when i not scroll down, ajax data is not loaded then click function is working.
i'm confuse why this happened. i used following triggers below but not success.
on()
click()
bind()
load()
delegate()
i'm sending you code. this is code below. Please help me to sort out.
$(window).ready(function(){
$(".like").on("click", function(){
var id = $(this).attr('data');
// alert(id);
$.ajax({
url: "/stores/addLike",
type: 'GET',
data: {
id: id
},
error: function (data) {
console.log(data);
},
success: function (data) {
console.log(data);
if(data == "liked"){
alert('Sorry, you have already liked this beat.');
}else if(data == "notlogin"){
alert('Please login first to like a beat.');
window.location = "https://demo.amplifihub.com/login";
}else{
$(".likes"+id).text(data);
}
}
});
});
});
instead of $(".like").on("click", function(){ }); use $(document).on("click", ".like", function(){}); or use any static parent dom element to preserve the DOM event. I believe you are generating .like class element on scroll ajax call.
I am making few ajax requests in my jQuery file. On success of these jQuery requests, I wrote few on click events which are not working.
This is my code
$(document).ready(function (){
$.ajax ({
type: "POST",
url: 'myServlet',
async: false,
success: function (response) {
id = parseInt(response);
setOutputEvents();
}
});
function setOutputEvents() {
for (var queryNumber = 0; queryNumber <= id; queryNumber++) {
$.ajax({
type: "POST",
url: 'myOtherServlet',
data: {queryNumber: queryNumber},
success: success,
async: false
});
var success = function (response) {
//some code here
generateTable();
}
}
}
function generateTable () {
//some code here
pagination();
}
function pagination(){
$(".class").click(function(event) {
alert();
});
}
$("#me").on("click", function(){
alert("me is triggered");
});
});
I understand making multiple ajax requests is a bad programming practice but what could be the reason for on click events not getting triggered?
These are the onclick events which are not working.
function pagination(){
$(".class").click(function(event) {
alert();
});
}
$("#me").on("click", function(){
alert("me is triggered");
});
I am using Google Chrome Version 39.0.2171.95 on Windows 7.
Please do let me know if any further information is necessary.
Since you use ajax to load even the initial content it seems, .class / #me html elements likely do not exist on initial page load of the DOM. As you didn't post html, i'm guessing this is the case.
Thus, you need to use a delegated event click handler to respond to it
so, you would change
$("#me").on("click", function(){
to
$(document).on("click", "#me", function(){
and so forth to link it to the parent element that does exist, the document itself.
This would work:
$(".class").on("click", function(){
alert("me is triggered");
});
function generateTable () {
//some code here
pagination();
}
function pagination(){
$(".class").trigger("click");
}
Some notes:
Event handler must be registered before triggering click.
Triggered click selector must match the class which has the click event registered.
Functions must be defined before the usage.
so i have a jquery function that does something on the click of an anchor tag.now i want to make the button unresponsive to jquery on subsequent clicks. what should i do?
what i am doing is changing the innerHTML of the anchor tag on the first click and doing an AJAX call and during this time period i want nothing to happen when the user click on the same anchor tag again.
This is how i handle clicks through jquery
$('.profileEdit label a').live('click', function () {
// do something
});
If i understood what you want you can just remove the 'onclick' attribute before the ajax call and set it up again at the end (success or fail).
#EDIT: final solution codes
function update(){
$("#bb").html('Updating');
$("body").off('click',"#bb");
$.ajax({
type: "POST",
url:"profileUpdate.asmx/HelloWorld",
data: "{ 'value': '" + document.getElementById(string).value + "'" + ",'column':'" + string + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
defaultSetter();
},
error: function (msg) {
defaultSetter();
}
});
}
function defaultSetter(){
$("#bb").html("Test");
$("body").on('click','#bb', update);
}
$(document).ready(function(){
defaultSetter();
});
jsfiddle: http://jsfiddle.net/V3AAF/
bb element is a button, not an anchor
Could you not just use one() if you only want the action to happen once on the first click?
$('.profileEdit label a').one('click', function () {
alert('This will only alert on the first click');
});
If you happened a handler for further clicks on that element, just use return false, to prevent anything from happening after the first click:
$('a').on('click', function () {
return false;
alert('first time!');
});
jsFiddle example.
I have a nifty little piece of Ajax code that loads in PHP.
http://www.moneyworrier.com/client-stories/
What happens is that when you click on a menu item on the left-hand navigation, it reloads a Div with content appropriate.
What it does however is loop through previous requests, which is bothersome (Click on any left hand item 3x and you will see what I mean). I think I need to find a function that does the equivalent of exit; and clears any post data.
My call in code is:
Video
And my JS looks like:
$(document).ready(function () {
$('a.media').click(function () {
var usr = $(this).attr('rel');
$("#displaystories").html('Retrieving..');
$.ajax({
type: "POST",
url: "/client-stories/media.php",
data: "showcode=" + usr,
success: function (msg) {
$("#displaystories").ajaxComplete(function (event, request, settings) {
$(this).html(msg);
});
}
});
});
});
You're binding a new listener to ajaxComplete on every click. Your success callback should just be:
success: function(msg) {
$("#displaystories").html(msg);
}
I have a relatively simple jQuery AJAX call wrapped in a function and I am testing my error functionality. The problem I am facing is the AJAX call happens too quickly! It is causing my 'H6' and '.loading' elements to start repeating. The behaviour I require is to remove the elements, then call the ajax.
function getAvailability(form) {
var str = $(form).serialize(),
warning = $('#content h6');
if ( warning.length > 0 ) {
$(warning).remove();
$('<div class="loading">Loading…</div>').insertAfter(form);
}
else
{
$('<div class="loading">Loading…</div>').insertAfter(form);
}
$.ajax({
type: "POST",
url: "someFile",
data: str,
success: function(calendar) {
$('.loading').fadeOut(function() {
$(this).remove();
$(calendar).insertAfter(form).hide().fadeIn();
});
},
error: function() {
$('.loading').fadeOut(function() {
$('<h6>Unfortunately there has been an error and we can not show you the availability at this time.</h6>').insertAfter(form);
});
}
});
return false;
}
I would love to sequence it like so -> Remove 'warning' from page, add .loading. Then trigger AJAX. Then fade out .loading, add & fade in warning/calendar dependent on success.
I have amended my original code, and I have got the function to behave as expected, primarily because I have disabled the submit button during the ajax process.
function getAvailability(form) {
var str = $(form).serialize(),
btn = $('#property_availability');
// Disable submit btn, remove original 'warning', add loading spinner
btn.attr("disabled", "true");
$('.warning').remove();
$('<div class="loading">Loading…</div>').insertAfter(form);
$.ajax({
type: "POST",
url: "public/ajax/returnAvailability1.php",
data: str,
success: function(calendar) {
$('.loading').fadeOut(function() {
$(this).remove();
$(calendar).insertAfter(form).hide().fadeIn();
});
},
error: function() {
$('.loading').fadeOut(function() {
$(this).remove();
$('<h6 class="warning">Unfortunately there has been an error and we can not show you the availability at this time.</h6>').insertAfter(form);
btn.removeAttr("disabled");
});
}
});
return false;
}
I believe that the original sequence was not working as expected due to the time delay created by the fadeOut() functions.
Instead of adding and removing warning, why not just show/hide leveraging ajaxStart and ajaxStop?
warning.ajaxStart(function() {
$(this).show();
}).ajaxStop(function() {
$(this).fadeOut();
});
If you need to sequence your events, then you should try using the deferred and promise methods that are a part of the jQuery.ajax API. This article does a good job of introducing them: http://www.bitstorm.org/weblog/2012-1/Deferred_and_promise_in_jQuery.html