jQuery fire function when element specific class change - javascript

I need to trigger an event when i add a specific class on button, but I have no idea how to make it listen to the class adding event.
I have something like this:
<script type="text/javascript">
$(document).ready(function() {
$(id_element).addClass("active");
//this function will fire on add "active" class to "id_button" element
function fireOnActiveClass() {
//do something
}
}
</script>
I can't touch code $(id_element).addClass("active");, for more reasons.
Currently I use jQuery 1.7.2
Could you please tell me how or which I need to know?

You are modifying the class of the control in your code. So why not simply call the click of the button when you change the class ?
$(id_element).addClass("active");
$(id_button).click();
$(id_button).click(function () {
if ($(this).hasClass) {
//do something
}
});

There is no event raised when a class changes. The alternative is to manually raise an event when you programatically change the class:
$(document).ready(function() {
$(id_element).addClass("active").trigger('classChange');
$(id_element).on('classChange', function() {
// do stuff
});
});

One other way would be to call a function right after adding the class like:
$.fn.classAdded = function() {
var $button = $(this);
if($button.hasClass('id_button')) {
// ...
}
return $button;
}
$(id_element).addClass("active").classAdded();

I have found solution using this jQuery Plugin: http://meetselva.github.io/attrchange/

Could this jQuery plugin be any help?
https://github.com/tormjens/jquery-dom-router
You can change the default element using
$.DOMRouter.defaults.element = '#element';
before initalizing the plugin.

Related

If there is a X class don't add a new Y class

I am a little confused with my JS (I am very new working with JS).
I already have
$('#left-nav-menu').hover(function () {
$(this).toggleClass('menu-desktop_open_hover')
});
I would like to achieve if there already is this class "menu-desktop_open_hover" and you click on the DIV with this class "menu-desktop_open_hover" DO NOT add a new class called "menu-desktop_open"
By default when you click the DIV with the class "menu-desktop_open_hover" it is adding a new class called "menu-desktop_open" (we need to keep this class for another things but not when the div is mouse-over/mouse-out)
Do anyone know how could I achieve it?
Thanks
You can use jQuery hasClass()
$('div').on('click', function() {
if ( $(this).hasClass("menu-desktop_open_hover") ) {
//Do something if it's true the class is applied...
}
});
You can use toggle like this:
$('div').on('click', function() {
if ( $(this).hasClass("menu-desktop_open_hover") ) {
$(this).toggleClass("menu-desktop_open"); // toggleClass() will help you.
}
});
Thank you #ProEvilz
Below my final code and it is working!
$('#left-nav-menu').hover(
function() {
$(this).toggleClass('menu-desktop_open_hover')
}
);
$('#left-nav-menu').on('click', function() {
if ($(this).hasClass("menu-desktop_open_hover")) {
$("#left-nav-menu").removeClass("menu-desktop_open");
}
});

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/

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 () {

Prototype event handler

I've defined the following HTML elements
<span class="toggle-arrow">▼</span>
<span class="toggle-arrow" style="display:none;">▶</span>
When I click on one of the elements the visibility of both should be toggled. I tried the following Prototype code:
$$('.toggle-arrow').each(function(element) {
element.observe('click', function() {
$(element).toggle();
});
});
but it doesn't work. I know everything would be much simpler if I used jQuery, but unfortunately this is not an option:
Instead of iterating through all arrows in the collection, you can use the invoke method, to bind the event handlers, as well as toggling them. Here's an example:
var arrows = $$('.toggle-arrow');
arrows.invoke("observe", "click", function () {
arrows.invoke("toggle");
});
DEMO: http://jsfiddle.net/ddMn4/
I realize this is not quite what you're asking for, but consider something like this:
<div class="toggle-arrow-container">
<span class="toggle-arrow" style="color: pink;">▶</span>
<span class="toggle-arrow" style="display:none; color: orange;">▶</span>
</div>
document.on('click', '.toggle-arrow-container .toggle-arrow', function(event, el) {
var buddies = el.up('.toggle-arrow-container').select('.toggle-arrow');
buddies.invoke('toggle');
});
This will allow you to have multiple "toggle sets" on the page. Check out the fiddle: http://jsfiddle.net/nDppd/
Hope this helps on your Prototype adventure.
Off the cuff:
function toggleArrows(e) {
e.stop();
// first discover clicked arow
var clickedArrow = e.findElement();
// second hide all arrows
$$('.toggle-arrow').invoke('hide');
// third find arrow that wasn't clicked
var arw = $$('.toggle-arrow').find(function(a) {
return a.identify() != clickedArrow.identify();
});
// fourth complete the toggle
if(arw)
arw.show();
}
Wire the toggle arrow function in document loaded event like this
document.on('click','.toggle-arrow', toggleArrows.bindAsEventListener());
That's it, however you would have more success if you took advantage of two css classes of: arrow and arrow-selected. Then you could easily write your selector using these class names to invoke your hide/show "toggle" with something like:
function toggleArrows(e) {
e.stop();
$$('.toggle-arrow').invoke('hide');
var arw = $$('.toggle-arrow').reject(function(r) {
r.hasClassName('arrow-selected'); });
$$('.arrow-selected').invoke('removeClassName', 'arrow-selected');
arw.show();
arw.addClassName('arrow-selected');
}

How Store and Disable Event of another element Temporary

I am looking for a way to manage the events. I have a hover function for element A, and click function for element B. I want to disable A`s hover function temporary while the second click of B.
I am looking for a way that not necessary to rewrite the hole function of A inside of B. Something very simply just like "Store and Disable Event, Call Stored Function"
I found some technique like .data('events') and console.log. I tired but failed, or maybe I wrote them in a wrong way.
Please help and advice!
$(A).hover();
$(b).click(
if($.hasData($(A)[0])){ // if A has event,
//STORE all the event A has, and disable
}else{
//ENABLE the stored event for A
}
);
Try this
var hoverme = function() {
alert('Hover Event Fired');
};
$('.A').hover(hoverme);
var i = 0;
$('.B').on('click', function(){
if(i%2 === 0){
// Unbind event
$('.A').off('hover');
}
else{
// Else bind the event
$('.A').hover(hoverme);
}
i++;
});
Check Fiddle
I think that what you want to do is something like this (example for JQuery 1.7.2):
$("#a").hover(function(){alert("test")});
$("#a")[0].active=true;
$("#b").click(function(){
if($("#a")[0].active){
$("#a")[0].storedEvents = [];
var hoverEvents = $("#a").data("events").mouseover;
jQuery.each(hoverEvents , function(key,handlerObj) {
$("#a")[0].storedEvents.push(handlerObj.handler);
});
$("#a").off('hover');
}else{
for(var i=0;i<$("#a")[0].storedEvents.length;i++){
$("#a").hover($("#a")[0].storedEvents[i]);
}
}
$("#a")[0].active = ($("#a")[0].active)==false;
});​
JSFiddle Example
But there are a couple of things that you must have in consideration:
This will only work if you add the events with JQuery, because JQuery keeps an internal track of the event handlers that have been added.
Each version of JQuery handles data("events") differently, that means that this code may not work with other version of JQuery.
I hope that this helps.
EDIT:
data("events") was an internal undocumented data structure used in JQuery 1.6 and JQUery 1.7, but it has been removed in JQuery 1.8. So in JQuery 1.8 the only way to access the events data is through: $._data(element, "events"). But keep in mind the advice from the JQuery documentation: this is not a supported public interface; the actual data structures may change incompatibly from version to version.
You could try having a variable that is outside the scope of functions a and b, and use that variable to trigger the action to take in function b on function a.
var state;
var a = function() {
if(!state) {
state = true;
// Add hover action and other prep. I'd create a third function to handle this.
console.log(state);
};
var b = function() {
if(state) {
state = false;
// Do unbinding of hover code with third function.
} else {
state = true;
// Do whatever else you needed to do
}
}
Without knowing more about what you're trying to do, I'd try something similar to this.
It sounds like you want to disable the click hover event for A if B is clicked.
$("body").on("hover", "#a", function(){
alert("hovering");
});
$("#b").click( function(){
$("body").off("hover", "#a", function() {
alert("removed hovering");
});
});
You can use the jQuery off method, have a look at this fiddle. http://jsfiddle.net/nKLwK/1/
Define a function to assign to hover on A element, so in b click, call unbind('hover') for A element and in second click on b element define again a function to hover, like this:
function aHover(eventObject) {
// Todo when the mouse enter object. You can use $(this) here
}
function aHoverOut(eventObject) {
// Todo when the mouse leave the object. You can use $(this) here
}
$(A).hover(aHover, aHoverOut);
// ...
$(b).click(function(eventObject) {
if($.hasData($(A)[0])){ // if A has event,
$(A).unbind('mouseenter mouseleave'); // This is because not a event hover, jQuery convert the element.hover(hoverIn, hoverOut) in element.bind('mouseenter', hoverIn) and element.bind('mouseleave', hoverOut)
}else{
$(A).hover(aHover, aHoverOut);
}
});
There are provably better ways to do it, but this works fine, on document ready do this:
$("#a")[0].active=false;
$("#b").click(function(){
$("#a")[0].active = ($("#a")[0].active)==false;
if($("#a")[0].active){
$("#a").hover(function(){alert("test")});
}else{
$("#a").off('hover');
}
});
JSFiddle example
You can use .off function from jQuery to unbind the hover on your "a" element.
function hoverA() {
alert('I\'m on hover');
}
$('#a').hover( hoverA );
var active = true;
$('#b').on('click', function(){
if(active){
$('#a').off('hover');
active = false;
} else{
$('#a').hover(hoverA);
active = true;
}
});
Live demo available here : http://codepen.io/joe/pen/wblpC

Categories