jquery addClass and removeClass issues - javascript

I am having strange issues with jQuery and adding and removing classes. I'm trying to see on success of a json request, that for the particular hyper link, it should call addClass and removeClass to add/remove particular css properties. When I click on it, it NEVER works, but when I try the css classes independently, they work fine. Is there something I'm missing here? Thanks for the input.
$(document).ready(function() {
$('.add_link').bind("click", function(e) {
$.getJSON("/add/", function(json) {
if (json.SUCCESS != null) {
$(this).removeClass('blue_button_link').addClass('gray_out_button_link');
}
});
});
});

$(document).ready(function() {
$('.add_link').bind("click", function(e) {
// cache it in a local variable.
var $this = $(this);
$.getJSON("/add/", function(json) {
if (json.SUCCESS != null) {
$this.removeClass('blue_button_link').addClass('gray_out_button_link');
}
});
});
});

In event handler you have another context, so you cannot use this how you want. Try:
$(document).ready(function() {
var link = $('.add_link');
link.bind("click", function(e) {
$.getJSON("/add/", function (json) {
if (json.SUCCESS != null) {
link.removeClass('blue_button_link').addClass('gray_out_button_link');
}
});
});
});
Or:
$(document).ready(function() {
$('.add_link').bind("click", function(e) {
var link = $(this);
$.getJSON("/add/", function (json) {
if (json.SUCCESS != null) {
link.removeClass('blue_button_link').addClass('gray_out_button_link');
}
});
});
});

Related

jQuery - preventDefault() in .each function

I want to use preventDefault() in .each function for collection of buttons and its not working. When I use it with one .click function it works fine but inside .each is not
Whan am I doing wrong?
Here is my .js code
$(document).ready(function() {
var findingStatus = $('#findingStatus').attr('finding-status-type');
var findingLike = $('#finding_like_btn');
var findingDislikeBox = $('.finding_dislike_add');
var findingDislikeCollection = $('.finding_dislike_add_btn')
var findingUnlike = $('#finding_unlike_btn');
var findingDislikeRemoved = $('#finding_dislike_removed');
var alertBox = $('.alert-box').hide();
if (findingStatus == 0) {
findingDislikeBox.show();
findingUnlike.hide();
findingDislikeRemoved.hide();
}
else if (findingStatus == 1) {
findingDislikeBox.hide();
findingUnlike.show();
findingDislikeRemoved.hide();
}
else if (findingStatus == 2) {
findingDislikeRemoved.show();
findingUnlike.show();
findingDislikeBox.hide();
findingLike.hide();
}
findingDislikeCollection.each(function() {
var findingDislike = $(this).clone();
var url = findingDislike.attr("href");
findingDislike.click(function(event) {
event.preventDefault();
$.ajax({
url: url,
type: "POST",
dataType: "json",
success: function(data) {
if (data.profileState == 1) {
$('#dislike_count_btn').text('Odrzuć' + data.DislikeCount);
findingDislikeBox.hide();
findingDislikeRemoved.show();
findingUnlike.show();
//findingUnDislike.show();
//findingUnDislike.attr('disabled', false );
//findingUnDislike.text('Cofnij');
}
else {
alertBox.show();
if ($('.alert-box-msg').length==0) {
$('.alert-area').prepend('<p class="alert-area alert-box-msg">Żeby korzystać z tej funkcji musisz być zalogowany.</p>');
}
findingDislike.attr('disabled', false );
}
},
error: function() {
alert('Problem z serwerem, spróbuj ponownie za kilka minut.');
findingDislike.attr('disabled', false );
}
});
});
});
$('html').click(function (e) {
if (!$(e.target).hasClass('alert-area')) {
$('.alert-box').hide();
findingDislike.attr('disabled', false );
}
});
});
Thanks for answer
You are cloning the element with .clone which means you're not actually attaching an event listener to anything in the DOM. Cloned elements must be manually inserted into the DOM with JavaScript for them to have any effect.
This is not a correct way. Following should work:
findingDislikeCollection.click(function(event){
var findingDislike = $(this);
var url = findingDislike.attr("href");
//AJAX call
event.preventDefault();
});
More details on click event are given here:
https://api.jquery.com/click/

focusin event using on not firing

I am attempting to perform some action on the foucsin of the textbox. However, for some reason the event never fires.
$(".ddlAddListinTo li").click(function () {
var urlstring = "../ActionTypes";
$.post(urlstring, function (data) {
$(window.open(urlstring, 'Contacts', 'width=750, height=400')).load(function (e) {
// Here "this" will be the pop up window.
$(this.document).find('#txtAutocompleteContact').on({
'focusin': function (event) {
alert('You are inside the Contact text box of the Contacts Popup');
}
});
});
});
});
When doing it that way, you generally have to find the body or use contents() to access the contents, as in
$(this.document).contents().find('#txtAutocompleteContact')
but in this case using a little plain javascript seems more appropriate :
$(".ddlAddListinTo li").on('click', function () {
var urlstring = "../ActionTypes";
$.post(urlstring, function (data) {
var wind = window.open(urlstring, 'Contacts', 'width=750, height=400');
wind.onload = function() {
var elem = this.document.getElementById('txtAutocompleteContact');
$(elem).on('focus', function() {
alert('You are inside the Contact text box of the Contacts Popup');
});
}
});
});

Saving CSS State Jquery Cookie

I've been trying to implement a way to save the CSS class that gets added on click to each item. I'm not sure how to go about it since each item has a different ID. That idea is that a user can revisit a page, and still have their items selected. I tried looking up other examples, but most only involved saving the body css and not an array of ids. I tried with Jquery Cookie but to no avail, any help would be greatly appreciated.
$('.select_it, .myState').on('click', function(e) {
var id = $(this).attr('id');
isRadio = $(this).data('status');
if(isRadio) {
if ($(this).hasClass('myState')) {
$(this).removeClass('myState');
} else {
$('.select_it').removeClass('myState');
$(this).addClass('myState');
}
$('.nextbutton').fadeTo("slow", 1.0, function() {
});
jsRoutes.controllers.Builder.selectedOption(id).ajax({
success : function(data) {
}
});
} else {
$('.nextbutton').fadeTo("slow", 1.0, function() {
});
$(this).toggleClass('myState');
jsRoutes.controllers.Builder.selectedOption(id).ajax({
success : function(data) {
}
});
}
});
Solution:
var state = {};
$('.nextbutton').click(function () {return false;});
if (localStorage.getItem("state") === null) {
//
} else {
$('.nextbutton').fadeTo("slow", 1.0, function() {
$('.nextbutton').unbind('click');
});
state = JSON.parse(localStorage["state"]);
}
$('.select_it, .myState').each(function(i, obj) {
if(state[obj.id] == 'myState') {
$(this).addClass('myState');
}
});
$('.select_it, .myState').on('click', function(e) {
var id = $(this).attr('id');
isRadio = $(this).data('status')
if(isRadio) {
$('.nextbutton').fadeTo("slow", 1.0, function() {
$('.nextbutton').unbind('click');
});
$('.myState').each(function(index, element){
$(this).removeClass('myState');
$(this).addClass('select_it');
state[element.id]='select_it';
});
$(this).addClass('myState');
state[id]='myState';
jsRoutes.controllers.Builder.selectedOption(id).ajax({success : function(data) {}});
} else {
if ($(this).hasClass('select_it')) { // TOGGLE ON
state[id]='myState';
$(this).removeClass('select_it');
$(this).addClass('myState');
} else { // TOGGLE OFF
state[id]='select_it';
$(this).removeClass('myState');
$(this).addClass('select_it');
}
jsRoutes.controllers.Builder.selectedOption(id).ajax({success : function(data) {}});
}
localStorage['state'] = JSON.stringify(state);
});
Cookie can only store a string. I would also consider using localStorage rather than cookie...and use cookie as fallback for older browsers that don't support localStorage.
If you create an object using element ID's as keys, you can use JSON.stringify to create string to store and use JSON.parse to convert string to object again.
/* example populated object, only need an empty object to start*/
var ui_state={
ID_1:'someClass',
ID_2:'inactiveClass'
}
Then within event handlers:
$('#ID_1').click(function(){
var newClass= /* logic to dtermine new class*/
$(this).addClass(newClass);
storeStateToLocal(this.id, newClass);
});
/* simplified store method*/
function storeStateToLocal(element_id, newClass){
ui_state[element_id]= newClass;/* update ui_state object*/
if(window.locaStorage != undefined){
localStorage.setItem('ui_state', JSON.stringify( ui_state) );
}else{
/* stringify to cookie*/
}
}
On page load can iterate over the object:
var ui_state= getStateFromLocal();/* if none in storage, return false*/
if(ui_state){
$.each(ui_state,function( element_id, currClass){
$('#'+element_id).addClass(currClass);
});
}else{
ui_state={};/* create empty object if none already in storage*/
}
Hmm not 100% sure, but is it something like this what you want?
$('.select_it').each(function(){
if ($(this).attr('id') != $.cookie(cookieName)) {
$(this).removeClass('myState');
} else {
$(this).addClass('myState');
}
});
Or maybe more like this:
$('.select_it, .myState').on('click', function(e) {
$('.select_it').removeClass('myState');
$(this).addClass('myState');
// more code
});

Trigger event not getting called

I'm using jQuery autoResize plugin based on James Padolsey.
In that plugin i'm trying to bind events and when i do
$(this).trigger('keydown.dynSiz',doResize); within hideXDiv() function
doResize doesn't get called... but $(this).trigger('keydown.dynSiz',doResize); in showXDiv() gets called.
Below is the code
textarea
.unbind('.dynSiz')
.bind('keyup.dynSiz', doResize)
.bind('keydown.dynSiz', doResize)
.bind('focus',showXDiv)
.bind('focusout',hideXDiv)
.bind('change.dynSiz', doResize);
});
doResize = function() {
alert("...");
}
showXDiv = function()
{
if(id != null)
{
$(this).trigger('keydown.dynSiz',doResize); //get called!
$($(this).attr('mydiv')).show();
}
}
hideXDiv = function()
{
if(id != null)
{
$(this).trigger('keydown.dynSiz',doResize); //this trigger doesn't happen....
$($(this).attr('mydiv')).slideUp();
}
}

setInterval with other jQuery events - Too many recursions

I'm trying to build a Javascript listener for a small page that uses AJAX to load content based on the anchor in the URL. Looking online, I found and modified a script that uses setInterval() to do this and so far it works fine. However, I have other jQuery elements in the $(document).ready() for special effects for the menus and content. If I use setInterval() no other jQuery effects work. I finagled a way to get it work by including the jQuery effects in the loop for setInterval() like so:
$(document).ready(function() {
var pageScripts = function() {
pageEffects();
pageURL();
}
window.setInterval(pageScripts, 500);
});
var currentAnchor = null;
function pageEffects() {
// Popup Menus
$(".bannerMenu").hover(function() {
$(this).find("ul.bannerSubmenu").slideDown(300).show;
}, function() {
$(this).find("ul.bannerSubmenu").slideUp(400);
});
$(".panel").hover(function() {
$(this).find(".panelContent").fadeIn(200);
}, function() {
$(this).find(".panelContent").fadeOut(300);
});
// REL Links Control
$("a[rel='_blank']").click(function() {
this.target = "_blank";
});
$("a[rel='share']").click(function(event) {
var share_url = $(this).attr("href");
window.open(share_url, "Share", "width=768, height=450");
event.preventDefault();
});
}
function pageURL() {
if (currentAnchor != document.location.hash) {
currentAnchor = document.location.hash;
if (!currentAnchor) {
query = "section=home";
} else {
var splits = currentAnchor.substring(1).split("&");
var section = splits[0];
delete splits[0];
var params = splits.join("&");
var query = "section=" + section + params;
}
$.get("loader.php", query, function(data) {
$("#load").fadeIn("fast");
$("#content").fadeOut(100).html(data).fadeIn(500);
$("#load").fadeOut("fast");
});
}
}
This works fine for a while but after a few minutes of the page being loaded, it drags to a near stop in IE and Firefox. I checked the FF Error Console and it comes back with an error "Too many Recursions." Chrome seems to not care and the page continues to run more or less normally despite the amount of time it's been open.
It would seem to me that the pageEffects() call is causing the issue with the recursion, however, any attempts to move it out of the loop breaks them and they cease to work as soon as setInterval makes it first loop.
Any help on this would be greatly appreciated!
I am guessing that the pageEffects need added to the pageURL content.
At the very least this should be more efficient and prevent duplicate handlers
$(document).ready(function() {
pageEffects($('body'));
(function(){
pageURL();
window.setTimeout(arguments.callee, 500);
})();
});
var currentAnchor = null;
function pageEffects(parent) {
// Popup Menus
parent.find(".bannerMenu").each(function() {
$(this).unbind('mouseenter mouseleave');
var proxy = {
subMenu: $(this).find("ul.bannerSubmenu"),
handlerIn: function() {
this.subMenu.slideDown(300).show();
},
handlerOut: function() {
this.subMenu.slideUp(400).hide();
}
};
$(this).hover(proxy.handlerIn, proxy.handlerOut);
});
parent.find(".panel").each(function() {
$(this).unbind('mouseenter mouseleave');
var proxy = {
content: panel.find(".panelContent"),
handlerIn: function() {
this.content.fadeIn(200).show();
},
handlerOut: function() {
this.content.slideUp(400).hide();
}
};
$(this).hover(proxy.handlerIn, proxy.handlerOut);
});
// REL Links Control
parent.find("a[rel='_blank']").each(function() {
$(this).target = "_blank";
});
parent.find("a[rel='share']").click(function(event) {
var share_url = $(this).attr("href");
window.open(share_url, "Share", "width=768, height=450");
event.preventDefault();
});
}
function pageURL() {
if (currentAnchor != document.location.hash) {
currentAnchor = document.location.hash;
if (!currentAnchor) {
query = "section=home";
} else {
var splits = currentAnchor.substring(1).split("&");
var section = splits[0];
delete splits[0];
var params = splits.join("&");
var query = "section=" + section + params;
}
var content = $("#content");
$.get("loader.php", query, function(data) {
$("#load").fadeIn("fast");
content.fadeOut(100).html(data).fadeIn(500);
$("#load").fadeOut("fast");
});
pageEffects(content);
}
}
Thanks for the suggestions. I tried a few of them and they still did not lead to the desirable effects. After some cautious testing, I found out what was happening. With jQuery (and presumably Javascript as a whole), whenever an AJAX callback is made, the elements brought in through the callback are not binded to what was originally binded in the document, they must be rebinded. You can either do this by recalling all the jQuery events on a successful callback or by using the .live() event in jQuery's library. I opted for .live() and it works like a charm now and no more recursive errors :D.
$(document).ready(function() {
// Popup Menus
$(".bannerMenu").live("hover", function(event) {
if (event.type == "mouseover") {
$(this).find("ul.bannerSubmenu").slideDown(300);
} else {
$(this).find("ul.bannerSubmenu").slideUp(400);
}
});
// Rollover Content
$(".panel").live("hover", function(event) {
if (event.type == "mouseover") {
$(this).find(".panelContent").fadeIn(200);
} else {
$(this).find(".panelContent").fadeOut(300);
}
});
// HREF Events
$("a[rel='_blank']").live("click", function(event) {
var target = $(this).attr("href");
window.open(target, "_blank");
event.preventDefault();
});
$("a[rel='share']").live("click", function(event) {
var share_url = $(this).attr("href");
window.open(share_url, "Share", "width=768, height=450");
event.preventDefault();
});
setInterval("checkAnchor()", 500);
});
var currentAnchor = null;
function checkAnchor() {
if (currentAnchor != document.location.hash) {
currentAnchor = document.location.hash;
if (!currentAnchor) {
query = "section=home";
} else {
var splits = currentAnchor.substring(1).split("&");
var section = splits[0];
delete splits[0];
var params = splits.join("&");
var query = "section=" + section + params;
}
$.get("loader.php", query, function(data) {
$("#load").fadeIn(200);
$("#content").fadeOut(200).html(data).fadeIn(200);
$("#load").fadeOut(200);
});
}
}
Anywho, the page works as intended even in IE (which I rarely check for compatibility). Hopefully, some other newb will learn from my mistakes :p.

Categories