can multiple click events be used on the same element? - javascript

$("#button1").click(function(e)
{
//action
});
$("#button2").click(function(e)
{
//do something
$("#button1").click(function(f)
{
//do something else
});
});
I have two buttons doing different actions.but if button 2 is clicked,i need button 1 to do a different task on the next click without the first function being executed.
any suggestions?

For that ,you need to use one variable scope for detect whether button 1 or 2 is click
var btn = 1; // default
$("#button1").click(function(e)
{
if(btn){
#button1 click
}
else{
#after button2 click
}
});
$("#button2").click(function(e)
{
btn = 2; //change value after button2 click
});

I suggest you look into jQuery's .on() and .off() capabilities.
http://api.jquery.com/on/
http://api.jquery.com/off/
As it says in the 'off' link above, you can create namespaces for your click events, so you can add and remove just the particular on and off events you like. Something like this:
$("#button1").on("click.myName", function(e){
//action
});
$("#button2").click(function(e){
//do something
$("#button1").off("click.myName").on("click.myOtherName", function(e) {
//do something else
});
});
This allows you to target your click events more directly, and not call .off() generically, wiping out all click events.

One method you could use is by unbinding any event listener before adding a new event listener to the button you want to change.
This can be done with the on() and off() functions in Jquery.
$("#button1").off('click').on('click',function(e)
{
//action
});
You can then do the same thing with button 2...
$("#button2").off('click').on('click',function(e)
{
//action
$("#button1").off('click').on('click',function(e)
{
//action
});
});
By doing this, the last on click that you set is the only one that will occur when you click that element.

You may try this once
$("#button1").click(function(e)
{
//action
});
$("#button2").click(function(e)
{
//do something
$("#button1").unbind();
$("#button1").bind('click', function(f)
{
//do something else
});
});
I hope this would work for you.

Related

Mouseover(show content) javascript

I'm new to JavaScript, I wonder, how can I make this:
I have menu item, then you click on it, info box pops up, there's X in corner, you close it and that's it. But my goal is not only on click show it, but even then you hover it. Here's script, if you need CSS let me know.
$('#help').appendTo('.navbar-container .level1');
$('#help a').click(function(e) {
e.preventDefault();
if($('#help').hasClass('active')) {
$('#help').removeClass('active');
} else {
$('#help').addClass('active');
}
$('#help-block').toggle();
});
$('#help-block .help-close').click(function(e) {
e.preventDefault();
$('#help-block').css('display','none');
$('#help').removeClass('active');
});
Thanks, people! Happy new year.
Multiple events can be bound to one .on() method, e.g:
$('#help a').on('click hover', function(e) {
// continue
});
Description: Attach an event handler function for one or more events to the selected elements.
Ref: .on() | jQuery API Documentation
Consider using this method instead.
Use .on() and mouseover like this:
$('#help').appendTo('.navbar-container .level1');
$('#help a').on("click mouseover",function(e) {
e.preventDefault();
if($('#help').hasClass('active')) {
$('#help').removeClass('active');
} else {
$('#help').addClass('active');
}
$('#help-block').toggle();
});
$('#help-block .help-close').on("click mouseover",function(e) {
e.preventDefault();
$('#help-block').css('display','none');
$('#help').removeClass('active');
});

Prevent certain functionality based on element clicked

I've got a button .btn-1 that when clicked also triggers click on .btn-2 I can't think of a way to do the following: when .btn-2 is clicked also trigger click on .btn-1 however in this case dismiss its functionality to trigger click on '.btn-2' to prevent infinite loop. Is there a way to achieve this?
You can pass additional data to your handler using .trigger() method:
$('.btn-2').on('click', function(event, skip) {
// if the skip parameter is a truthy value
// don't trigger the event
if ( !skip ) {
$('.btn-1').trigger('click', [true]);
}
});
$('.btn-2').trigger('click', [true]);
you can use a boolean that switches:
var done=true;
$('.btn-1').click(function(){
$('log').html($('log').html()+'bt1 pressed<br>')
if(done){
done=false;
$('.btn-2').click()
}
done=true;
})
http://jsfiddle.net/2o3k5wet/
A more elegant way to do this:
$('.btn-1, .btn-2').on('click', function() {
// do common stuff
if ($(this).is('.btn-1')) {
// do stuff only for 1
}
// do common stuff
});

Unbind and rebind click on css transition end

I'm having troubles with the .bind() and .unbind() features. When the button is clicked, it's supposed to change the color of the box. During this time, the button is disabled by unbinding the click function. However, I'm having issues rebinding the click when the css transition completes.
What I have so far is:
$('button').on('click', function(){
$('button').unbind('click');
$('.box').toggleClass('color');
$('.box').one('webkitTransitionEnd transitionend', function(e){
console.log('transition ended')
$('button').bind('click')
});
});
http://jsfiddle.net/t6xEf/
You need to pass the click handler when binding it. So create a function reference then use it while binding the handler.
function click() {
$('button').off('click.transition');
$('.box').toggleClass('color');
}
$('.box').on('webkitTransitionEnd transitionend', function (e) {
console.log('transition ended')
$('button').on('click.transition', click)
});
$('button').on('click.transition', click);
Demo: Fiddle
Also look at the usage of namespaces while registering/removing the handler because if there if some other click handler added to the button we don't want to disturb it
Also do not add a event handler inside another one
Also have a look at .one()
function click() {
$('.box').toggleClass('color');
}
$('.box').on('webkitTransitionEnd transitionend', function (e) {
console.log('transition ended')
$('button').one('click.transition', click)
});
$('button').one('click.transition', click);
Demo: Fiddle
I would use a flag instead of binding/rebinding the event handler:
var animating = false;
$('button').on('click', function() {
if (animating) return;
animating = true;
$('.box').toggleClass('color')
.on('webkitTransitionEnd transitionend', function(e) {
animating = false;
});
});
http://jsfiddle.net/t6xEf/1/
Do not unbind. Use a boolean:
var onTrans = false;
$('button').on('click', toggle);
function toggle() {
if (!onTrans){
$('.box').toggleClass('color');
onTrans = true;
$('.box').on('webkitTransitionEnd transitionend', function (e) {
onTrans = false;
});
}
}
http://jsfiddle.net/jp8Vy/
This is surely not what you want to do. It seems overly complex, and I can't imagine a good use case scenario.
That being said, you need to reattach the functionality to be performed in the final bind statement. You call the function to bind to the click event, but don't tell the function what to attach.
You need something like this:
$('button').bind('click', function() { ... });
However, that probably isn't what you really want. It sounds like you just want to set the button's "disabled" attribute to false, then to true after the animation.

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

jquery selector help. Everything but the specified selector

I have the following function to open an overlay menu:
$('.context-switch').click(function() {
$(".context-switch-menu").toggle();
});
To hide the menu, I would like the user to be able to click on any area outside ".context-switch-menu"
I am trying with :not() but with no success..
$('body').click(function(e) {
if ($(e.target).hasClass('context-switch')) {
return;
}
$(".context-switch-menu").hide();
});
$('.context-switch').click(function() {
$(".context-switch-menu").toggle();
return false;
});
The reason this can be difficult is because of event bubbling.
You can try something like this:
$('.context-switch').click(function(e) {
e.stopPropagation();
$(".context-switch-menu").toggle();
});
$(".context-switch-menu").click(function(e){
e.stopPropagation();
});
$("body").click(function(e){
$(".context-switch-menu").hide();
});
The e.stopPropagation() prevents the click event from bubbling to the body handlers. Without it, any click to .context-switch or .context-switch-menu would also trigger the body event handler, which you don't want, as it would nullify the effect of the .context-switch click half the time. (ie, if the state is hidden, and then you click to show, the event would bubble and trigger the body handler that would then hide the .context-switch-menu again.)
Without testing, would something like this work?:
$('.context-switch').click(function() {
$(".context-switch-menu").show();
});
$(document).click(function() {
$(".context-switch-menu").hide();
});
Instead of using document, 'html' or 'body' may work as well.
$(document).on('click', function(e) {
if (e.target.className !='context-switch-menu') {
$(".context-switch-menu").hide();
}
});
Just an idea here, based on what what others have suggested in the past:
$(document).click(function(e){
//this should give you the clicked element's id attribute
var elem = $(e.target).attr('classname');
if(elem !== 'context-switch-menu'){
$('.context-switch-menu').slideUp('slow');
//or however you want to hide it
}
});
try this, we don't want to call a function when you clicked on the element itself, and not when we click inside the element. That's why we need 2 checks.
You want to use e.target which is the element you clicked.
$("html").click(function(e){
if( !$(e.target).is(".context-switch-menu") &&
$(e.target).closest(".context-switch-menu").length == 0
)
{
alert("CLICKED OUTSIDE");
}
});
Live fiddle: http://jsfiddle.net/Xc25K/1/

Categories