Turn function on and off - javascript

I have a jQuery tip function. I would like to create a button to turn on and turn off the function. I want it to be on by default.
Is it possible to create a link to turn on and off a function?

You can dynamically add and subtract event handlers with the bind and unbind functions.
$("#id").click( function() {
if ( HANDLER_IS_SET )
$("#button").unbind( "click");
else
$("#button").bind( "click", myEventHandlerFunction );
}

You can set a boolean to check if it's on or off, or bind and unbind a function.
var isOn = false;
$("#button").click(function(){ isOn = !isOn; });
$("#executebutton").click(MyFunction);
function MyFunction()
{
if (!isOn) return;
// do stuff
}
or
$("#button").click
(
function()
{
if ($("#executebutton").data("events").click != undefined)
$("#executebutton").unbind("click");
else
$("#executebutton").bind("click", MyFunction);
}
);

A little more info is needed, but you could use a global variable to toggle an if statement within the function so it doesn't execute anything, but the function will still be called.

Related

Choose only the first button

I'm trying to do that only one can happen, if you click yes or no. As it is now if you click "no" in the first time and "yes" in the second time, it will execute it twice .
function confirm() {
$("#no").one("click", function(){
return false;
});
}
$("#yes").one("click", function () {
//do something
});
thanks for help
Both events are attached at document.ready I assume, which means they will remain active indefinitely unless you specify otherwise.
The following approach is fairly basic, just set a variable 'hasClicked' to false. And as soon as either one of them is clicked, set 'hasClicked' to true. Each button has an if-structure that only executes the code IF 'hasClicked' is false.
Try the following:
var hasClicked = false;
function confirm(){
$("#no").one("click", function(){
if (!hasClicked){
hasClicked = true;
return false;
}
});
$("#yes").one("click", function () {
if (!hasClicked) {
hasClicked = true;
//do something
}
});
}
As you can't unbind an event binded with one() check this answer
So you'll have to work around like this:
function confirm() {
$("#no").bind("click", function(){
$(this).unbind(); // prevent other click events
$("#yes").unbind("click"); // prevent yes click event
// Do your stuff
});
}
$("#yes").bind("click", function () {
$(this).unbind();
$("#no").unbind("click");
// Do your stuff
});
Assign your buttons a class called confirmation. Set a event handler based on class. Read the value of the button to decide what you want to do.
$(".confirmation").one("click", function(){
if($(this).val() === 'yes'){
//do something
}else{
return false;
}
}

jQuery unbind click event function and re-attach depending on situation

The code below I use to create a sliding menu. I need to know how to unbind the function attached to the click event and re-attach it some other time. (using jQuery 1.7.2)
$(document).ready(function(){
$('.section').hide();
$('.header').click(function(){
if($(this).next('.section').is(':visible'))
{
$('.section:visible').slideUp()
$('.arrows:visible').attr("src","right.gif")
}
else
{
$('.section').slideUp();
$(this).next('.section').slideToggle();
$(this).find('.arrows').attr("src","down.gif")
});
});
The code below is what I have so far
$('#printVers').click(function(){
if($('#formVersion').val() != "Print")
{
$('.header').unbind('click');
}
else
{
//else re-attach functionality?
}
});
Thanks
Simply make a named function. You can go low tech here and back to basics to unbind and reattach specific events.
function doStuff()
{
if($(this).,next('.section').is(':visible'))
...
}
$('.header').on('click', doStuff);
$('.header').off('click', doStuff);
Instead of unbind and re-bind, I suggest you to add a simple class to .header and check for the class in the click handler. See below,
$('#printVers').click(function(){
if($('#formVersion').val() != "Print")
{
$('.header').addClass('dontClick');
} else {
$('.header').removeClass('dontClick');
}
});
And in your .header click handler,
$('.header').click(function(){
if ($(this).hasClass('dontClick')) {
return false;
}
//rest of your code
If you insist on having a unbind and bind, then you can move the handler to a function and unbind/bind the function any number of time..
You can try something like this.
$('#printVers').click(function(){
if($('#formVersion').val() != "Print")
{
$('.header').addClass('clickDisabled');
}
else
{
$('.header').removeClass('clickDisabled');
}
});
And then in the click handler check for this class.
$(document).ready(function(){
$('.section').hide();
$('.header').click(function(){
if(!$(this).hasClass('clickDisabled')){
...
...
}
});
});
Why not make that top section a function, and then call it in your else statement?
You could try setting a variable as a flag. var canClick = ($('#formVersion').val() != 'Print'); Then in the click handler for your .header elements check to see if canClick is true before executing your code.
If you still want to remove the handler you can assign the events object to a variable. var eventObj = #('.header').data('events'); That will give you an object with all the handlers assigned to that object. To reassign the click event it would be like $('.header').bind('click', eventObj.click[0]);
After trying so hard with bind, unbind, on, off, click, attr, removeAttr, prop I made it work.
So, I have the following scenario: In my html i have NOT attached any inline onclick handlers.
Then in my Javascript i used the following to add an inline onclick handler:
$(element).attr('onclick','myFunction()');
To remove this at a later point from Javascript I used the following:
$(element).prop('onclick',null);
This is the way it worked for me to bind and unbind click events dinamically in Javascript. Remember NOT to insert any inline onclick handler in your elements.
You could put all the code under the .click in a separated function
function headerClick(){
if($(this).next('.section').is(':visible'))
{
$('.section:visible').slideUp()
$('.arrows:visible').attr("src","right.gif")
}
else
{
$('.section').slideUp();
$(this).next('.section').slideToggle();
$(this).find('.arrows').attr("src","down.gif")
}
}
and then bind it like this:
$(document).ready(function(){
$('.section').hide();
$('.header').click(headerClick);
});
$('#printVers').click(function(){
if($('#formVersion').val() != "Print")
{
$('.header').unbind('click');
}
else
{
$('.header').click(headerClick);
}
});

jquery how to combine two selectors to second function of single toggle event

If I have a regular toggle function bound to a click event
$('#work-content a').toggle(
function() {
// first click stuff
}, function() {
// second click stuff
}
);
But, I also need to bind $(document).click event to the second function somehow. My logic is probably off so I'm sure a new solution is necessary.
Functionality is 1) do something when link is clicked then 2) do the opposite when the link is clicked again or if the outside of the #work-content div is clicked.
Just extract the anonymous function and give it a name:
var thatFunction = function () {
...
}
$('#work-content a').toggle(
function() {
// first click stuff
},
thatFunction);
$(document).click(thatFunction);
the toggle function is used to hide/show your div and should not be used to maintain state of an event. just use another local variable for this and also define two functions perform your two different actions and pass the function pointer as callback to your event listener.
thus:
var linkClicked=false;
function fun1(){}
function fun2(){}
$('#work-content a').click(
function() {
if(!linkClicked)
fun1();
else
fun2();
});
$("body").click(function(){
if($(event.target).closest("#work-content")===null) //to make sure clicking inside your div does not trigger its close
{
fun2();
}
});
linkClicked = false;
$('#work-content .pic a').click(function(event) {
event.preventDefault();
var c = $(this);
if (!linkClicked) {
values = workOpen($(this));
} else {
workClose(c, values);
}
$('body').one('click',function() {
workClose(c, values);
});
});
This solution was exactly what I needed for what it's worth.

How to trigger a function on a value that can change?

I have some functions that are triggered when an element is clicked. The elements are stored in an array. But the value that trigger the functions change. Here is the code for the function:
// first I store the element of a list in an array
var promo = new Array(),
indexOfTheElement = 3;
$('#list li').each(function(){
promo.push($(this));
});
$(myArray[indexOfTheElement]).click(function(){
indexOfTheElement--;
// Do something
return false;
});
Edit: The element of a list are stored in an array, and the function is triggered when you click an element of the list. For example if you click the third element, the function will be triggered, and then it must work when you click the second.
It could be a scope issue, but I believe you want to use bind() and unbind() on each function call. For instance:
var foo = function(){
myArray[index].unbind("click");
index--;
//do something
myArray[index].bind("click", foo);
return false;
}
Inside you event handler unhook current event handler and set the new one, simply declare the function (not use an anonymous function) when you set the click().
$(myArray[indexOfTheElement]).click(doSomething);
function doSomething()
{
$(myArray[indexOfTheElement]).off("click", doSomething);
$(myArray[--indexOfTheElement]).click(doSomething);
return false;
}
try using live() and code inside $(document).ready()
$(document).ready(function(){
var promo = new Array(),
indexOfTheElement = 3;
$('#list li').each(function(){
promo.push($(this));
});
$(myArray[indexOfTheElement]).live('click',function(){
indexOfTheElement--;
// Do something
return false;
});
});

How do I add a click handler to a class and find out which element was clicked?

I have been using the following method for adding a click event to an id, I was wondering if I could do the same with a class.... I have a number of items (which are created in a for each loop) and I need to be able to click them and then pickup which was clicked... here is my existing code
$('submit-button').bind('click', submit_click);
function submit_click() {
alert('I am clicked');
}
I was wondering if there is some way to pass in a variable into my function for the click so i can check the ID?? or similar
hence this
function submit_click(element) { // notice element
alert(element + ' clicked');
}
Any help really appreciated
Thank you
EDIT
I have tried the following and in debug "elem" is undefined...
$('.clear').bind('click', clear_click($(this)));
function clear_click(elem)
{
alert(elem.attr("id"));
}
WORKING SOLUTION
I have the working solution but I don't fully understand why, I would love to know why it works..
First of all I tried
$('.clear').bind('click', clear_click($(this)) );
This seemed to work "BUT" when I loaded the page it enter the "clear_click" method without being clicked - strange...
Then I tried this..
$('.clear').bind('click', function() { clear_click($(this)) } );
This works great! But I don't understand why I must pass a function and then within this function call my clear_click.
Can anyone explain why 1 works and the other doesn't?
Whenever I need to call a callback function or similar I should first open a function() and then call the method inside the function?
$(".yourclass").click ( function() {
$(this).attr ( "id" ); //S(this) returns the current element
});
and you can code like this
$('.yourclass').bind('click', function() { submit_click($(this)) });
function submit_click(elem)
{
alert ( elem.attr ("id" ) );
}
Edit
$('.clear').bind('click', function() { clear_click($(this)) });
function clear_click(elem)
{
alert(elem.attr("id"));
}
This will work fine for you.
Update
To answer your second question:
You can bind a function as a second argument when using the click event, but you cant bind a function and apply arguments. On the other hand, there is no need to send this as an argument to the clear_click function since the this keyword inside the function refers to the element itself:
So this works in your case:
$('.clear').bind('click', clear_click);
function clear_click() {
alert(this.id);
}
Sending this as an argument is not needed and bad coding:
$('.clear').bind('click', clear_click(this));
In the event handler, the first argument is the event object. You can extract the clicked element from that object using currentTarget or target. In jQuery, this always refers to the currentTarget in the event handler context:
var handler = function(e) {
var id = this.id; // this == e.currentTarget
}
$('submit').click(handler); // .click(fn) is shorthand for .bind('click', fn)
More examples:
$('submit').bind('click', function(e) {
console.log(e.target) // the target that was clicked on
console.log(e.currentTarget) // the element that triggered the click
console.log(this) // the same as above
});
Just add $(this) to your function, You don't need to send any parameters because you are still in the context of the clicked element.
function submit_click() { // notice element
alert($(this).attr('id') + ' clicked');
}
When you bind a handler to a function, the clicked element will be the first argument
$('.submit-button').click(submit_click);
function submit_click(element){
//element is the .submit-buttom element
alert(element+' was clicked');
alert($(element)+' was clicked');
}
This should work:
$('.submit-button').bind('click', submit_click($(this)));
function submit_click(element) { // notice element
alert($(element).attr("id") + ' clicked');
}

Categories

Resources