Change class but click not recognizing the new class - javascript

I have the following html:
<div class="showMap" id="mapVis" style="cursor:pointer">(Show map)</div>
<div id="map">hello world</div>
Div #map is hidden as shown below (there's a reason for hiding it this way, it holds a google map), then I want to click (Show map) and the div appears. This is ok. Then I change the class and the html of the #mapVis div and want the next click to hide #map - but it doesn't. Honestly I don't know what its doing but its as if it ignores the new class and reverts to the actions as if previous class was still attached to the #mapVis div.
Here's the JQuery:
var map2 = $('#map');
map2.css('position','absolute').css('left','-9999em');
$('.showMap').click(function(){
map2.hide().css('position','relative').css('left','0em').slideDown();
$('#mapVis').removeClass('showMap').addClass('hideMap').html('(Hide map)');
});
$('.hideMap').click(function(){
map2.css('position','absolute').css('left','-9999em');
$('#mapVis').removeClass('hideMap').addClass('showMap').html('(Show map)');
});
Here's a fiddle

Since your selectors have to be evaluated dynamically you need to use event delegation.
When you use normal event registration the selectors are evaluated only at the time of event registration and any changes done on the element will not reflect in the registered handlers.
var map2 = $('#map');
map2.css('position', 'absolute').css('left', '-9999em');
$(document).on('click', '.showMap', function () {
console.log('hey2');
$('#map').hide().css('position', 'relative').css('left', '0em').slideDown();
$('#mapVis').removeClass('showMap').addClass('hideMap').html('(Hide map)');
});
$(document).on('click', '.hideMap', function () {
console.log('hey');
$('#map').hide();
$('#map').css('position', 'absolute').css('left', '-9999em');
$('#mapVis').removeClass('hideMap').addClass('showMap').html('(Show map)');
});
Demo: Fiddle

jsfiddle: http://jsfiddle.net/7At32/
this is a sample, BUT you can modify to your requirement
$('#mapVis').click(function () {
if ($(this).hasClass("showMap")) {
$('#map').show();
$(this).removeClass('showMap').addClass('hideMap').html('(Hide map)');
} else {
$('#map').hide();
$(this).removeClass('hideMap').addClass('showMap').html('(Show map)');
}
});

Related

Attach second click-event to an element after class name has been changed

I have a div with a class name a. I attach a click-event to this div like
$('.a').on('click', function() {
$(this).removeClass('a').addClass('b');
})
After this; element's class name changes from a to b. I want to attach second click event on .b like
$('.b').on('click', function() {
$(this).removeClass('b').addClass('c');
})
First click event works fine however second one does not fire. See my JSfiddle.
Attach the click even to a higher element in the DOM - when you change the class, the event bubbling up will change, e.g.
$("body").on("click", ".b", function() {
$(this).removeClass('b').addClass('c');
});
You can add the second event after the first one has fired:
$('.a').on('click', function() {
$(this).removeClass('a').addClass('b');
$('.b').on('click', function () { /* ... */ });
})
You're running the .b code at the beginning, when the element doesn't have class b. Try adding the new onClick handler in the code for your first onClick.
Code:
$('.a').on('click', function() {
$(this).removeClass('a').addClass('b');
$('.b').on('click', function() {
$(this).removeClass('b').addClass('c');
})
})
$(".a").click(function() {
$(this).removeClass("a").addClass("b");
$(".b").click(function() {
$(this).removeClass("b").addClass("c");
})
})

Enable and Disable a Span class based on an even in jQuery

I have a span class which should be hidden initially and visible after an event.
<span class="badge badge-xs badge-danger">2</span>
I need it to happen on the following code:
<script>
$(document).on("DOMSubtreeModified", "#history", function () {
//add code to make span class visible
});
</script>
Wht i need is to make the class hidden on page load and make it visible after a change in #history id in a paragraph..
How is it possible through jQuery ??
You can use .show() and .hide() to change an element visibility.
$("span.badge").hide(); // or make it hidden in css by default
$(document).on("DOMSubtreeModified", "#history", function () {
$("span.badge").show();
});
The property disabled are used on input type fields only, for example in a text field you wouldn't be able to type in it. But in a span it has no effect since you can't input anything by default.
For custom Events, you have two Options:
Work with Observer. You have one subscriber and a notifier.
function Observer(){
var subscriber = [];
return{
addSubscriber: function(func){
subscriber.push(func);
},
notify: function(){
for(var i = 0; i < subscriber.length; i++){
subscriber[i]();
}
}
}
}
var observer = new Observer();
function calledOnEvent(){
$(element).hide();
}
observer.addSubscriber(calledOnEvent);
function createTheEvent(){
//Logic
observer.notify();
}
You can use eventListener and the customEvent Object.
document.addEventListener('event', aFunction);
function createAEvent(){
var event = new Event('event');
document.dispatchEvent(event);
}
In pure Javascript is the support for customEvent not really good. jQuery has a wrapper for this .trigger(): http://api.jquery.com/trigger/

How to remove class after it been added

So I need a little bit of help. I'm playing around with addClass and removeClass and I can't seem to remove a class after it's set. What I basically want is:
When someone clicks an h3, it adds to its parent div class
When someone clicks a div with added class, class needs to be removed
First step I got out of way and it's working
$(function(){
$('div h3.itemTitle').on('click', function(){
$(this).parent().addClass('active').siblings().removeClass('active');
});
});
Now when I define:
$(function(){
$('div.active').on('click', function(){
$(this).removeClass('active');
});
});
It does nothing, as if it doesn't see classes. It sets only those set in onload...
Help, anyone?
The child element "h3.itemTitle" already had a click event listener on it and the parent can't actually capture the click event.
Your $('div.active').on('click', ...) never actually fires because you click the h3 not the div.
I recommend this approach: http://jsfiddle.net/c3Q6Q/
$('div h3.itemTitle').on('click', function () {
// saves time not to write $(this).parent() everything so i store in a _parent var
var _parent = $(this).parent();
if (_parent.hasClass('active')) {
_parent.removeClass('active');
} else {
_parent.addClass('active').siblings().removeClass('active');
}
});
Try
$('body').on('click','div.active', function(){$(this).removeClass('active');});
Instead of
$('div.active').on('click', function(){$(this).removeClass('active');});
I would go with this way:
$('div').on('click', function(e){
var el = e.target;
if($(el).is('h3') && $(el).hasClass('itemTitle')){
$(this).parent().addClass('active').siblings().removeClass('active');
}else if($(el).is('div') && $(el).hasClass('active')){
$(this).removeClass('active');
}
});
Not sure why every is talking about elements generated outside of the initial DOM load.
Here's a JSFiddle showing that it works: http://jsfiddle.net/H25bT/
Code:
$(document).ready(function() {
$('.itemTitle').on('click', function() {
$(this).parent().addClass('active').siblings().removeClass('active');
});
/* $('.parent').on('click', function() {
$(this).removeClass('active');
}); */
$('.clicky').on('click', function() {
$(this).parent().removeClass('active');
});
});
The reason it's not working for you is that if you put the removeClass click event on the parent div itself, clicking on the child text causes a conflict with which click handler to use, and it won't work out. Code works fine if you don't assign the click to the parent div itself.

Click event is not working for dynamically changed class in jquery

I have two class .btnn and .sleep_avail sometimes i changes the css of a anchor from .btnn to .sleep_avail
Now i have two function for anchor click
$('.btnn').click(function () {
alert('yes btn');
});
And Second one is
$('.sleep_avail').click(function () {
alert('yes sleep');
});
Now when i click on the anchor with class sleep_avail which is changed dynamically from btnn class the event written for btnn raised and i get response accordingly. But what i need is that the event for sleep_avail should be raised. Kindly help.
Anytime, you use dynamically created tags, you must use
$(document).on('#event','#selector',function () {...});
so here
$(document).on('click','.sleep_avail',function () {...});
Because event handlers bind to the currently elements, they have to exist on the page when .on()is called
Here is the working DEMO http://jsfiddle.net/ARBdU/
$(document).on('click','.btnn, .sleep_avail',function () {
if($(this).hasClass('btnn'))
{
...
}
else if($(this).hasClass('sleep_avail'))
{
...
}
});
try
$(document).on('click','.sleep_avail',function () {

Binding click function to dynamic divs

There will be number of such div created with unique div id,
when i click on click me it should show an alert for that productid,
i am doing it like
<div id="xyz{productid}">
Click Me
</div>
.....
<script type="text/javascript">
var uuid="{productid}"
</script>
<script src="file1.js">
code from file1.js
$(function () {
var d = "#xyz" + uuid;
$(d).click(function () {
alert("Hello" + uuid);
return false;
});
alert(d);
});
So code is also ok,but the basic problem with it is,
since i m doing it on category page where we have number of products,this function is getting bound to last product tile only,
I want it to be bound to that specific div only where it is been called
..............................
got a solution
sorry for late reply,was on weekend holiday, but i solved it by class type of architecture, where we create an object with each tile on page,and at page loading time we initialize all its class vars,so you can get seperate div id and when bind a function to it, can still use the data from its class variables, i m posting my code here so if any one want can use it,
UniqeDiv= new function()
{
var _this = this;
var _divParams = null;
var _uuid=null;
//constructor
new function(){
//$(document).bind("ready", initialize);
//$(window).bind("unload", dispose);
_uuid=pUUID;
initialize();
$('#abcd_'+_uuid).bind("click",showRatingsMe)
dispose();
}
function initialize(){
}
function showRatingsMe(){
alert(_uuid);
}
function dispose(){
_this = _divParams = null
}
}
//In a target file, im including this js file as below
<script type="text/javascript">
var pUUID="${uuid}";
</script>
<script type="text/javascript" src="http://localhost:8080/..../abc.js"></script>
You can use attribute selector with starts with wild card with jQuery on() to bind the click event for dynamically added elements.
$(document).on("click", "[id^=xyz]", function(){
//your code here
alert("Hello"+this.id);
return false;
});
I would add a class to each of your dynamic divs so that they are easier to query. In the following example, I'm using the class dynamic to tag the div's that are added dynamically and should have this click listener applied.
To attach the event, you can use delegated events with jQuery's on() function. Delegated events will fire for current and future elements in the DOM:
$(function() {
var d="#xyz"+uuid;
$(document).on('click', 'div.dynamic', function() {
alert("Hello"+uuid);
return false;
});
});
You can read more about event delegation here.
You can use
$("[id*='divid_']").click(function(){
});
but for this you need to make sure that all div IDs start with "divid_".

Categories