Click toggle with jquery/javascript - javascript

I want to click a table element and to have it do x the first click and if clicked again perform Y
<td class='p' id='e1' onclick="myFunction2()"><img src='person2.png'/></td>
Thats what I have for my HTML for one click just now, but I wish to change that so that an item can be selected, then if clicked again for a deselect it would then trigger a different function.

I'm going to assume (you didn't say) that you want the function to be called to alternate with every click:
$('#e1').on('click', function() {
// retrieve current state, initially undefined
var state = $(this).data('state');
// toggle the state - first click will make this "true"
state = !state;
// do your stuff
if (state) {
// do this (1st click, 3rd click, etc)
} else {
// do that
}
// put the state back
$(this).data('state', state);
});
This uses jQuery's .data feature to store the button's click state in the button element itself.
Alternatively, you could use an external variable, but you should enclose the callback in a closure (in this case an immediately invoked function expression) to prevent the variable from becoming a global variable:
(function() {
var state;
$('#e1').on('click', function() {
state = !state;
if (state) {
// do this (1st click, 3rd click, etc)
} else {
// do that
}
});
})();
If the .on call and the state variable declaration are inside a jQuery document.ready handler that would have the same effect.

Pretty basic, let me know if this is close to what you want.
http://jsfiddle.net/WNJ75/6/
<div id="e1">Click Me</div>
.
(function() {
var click_track = 1;
$("#e1").click(function() {
if (click_track == 1)
alert("do something");
else if (click_track == 2) {
alert("do something else and reset click");
click_track = 0;
}
click_track++;
});
})();

demo: http://jsfiddle.net/HJwJf/
Link the toggle method with;
$("button").toggle(function(){
$("body").css("background-color","green");},
function(){
$("body").css("background-color","red");},
function(){
$("body").css("background-color","yellow");}
);

You could create a new atribute on the HTML element named, for example, "clickCount", and use it inside your event handler as a counter.
Let's say you have a button like this one:
<button data-click-count='0' onclick="myFunction(this)">My Button</button>
And you have a function like this:
function myFunction(elt) {
// Gets the clicks count
var count = $(elt).data("click-count");
// Adds one to the click counter
$(elt).data("click-count", ++count);
if (count == 1)
doSomething();
else if (count == 2)
doSomethingElse();
}
Every time you click the button, you'll see an alert with the number of clicks you've made.
You can use the same method and apply it to your case.

Using a state variable. The state variable will swap between the values 0 and 1 on each click. Making use of state we can execute the corresponding function in fn array.
<td class='p' id='e1'><img src='person2.png'/></td>
$("td#e1.p").each(function(){
var state = 1, fn = [myFunction1, myFunction2];
$(this).click(function(){
return fn[state = 1 - state].apply(this, arguments);
});
});
Also, it's preferably to use proper event binding than inline JavaScript.

Related

How to pass a HTML control to another javascript function

I want to pass HTML control to another function inside JavaScript. I am calling a modal popup which has a input control and a save button.
The function in which i am calling the modal popup has entire GridView row as a parameter. I want to pass this to another javascript function which will be called on the button click inside of modal dialog.
I tried as below but it passes a string variable.
function ShowDialogPeoplePicker(id, requestType, cntrl) {
var row = cntrl.parentNode.parentNode;
var rowIndex = row.rowIndex - 1;
var Approvers = row.cells[1].getElementsByTagName("span")[0];
if (requestType == "AddApprovers") {
$('#btnAddApprover').removeAttr('onclick');
$('#btnAddApprover').attr('onClick', 'if (!setApprovers(\'' +cntrl + '\')) return false;');
}
}
The below function will be called on a button click and will set the values inside GridView row.
function setApprovers(cntrl)
{
var usernames= $("#hdnApproversName_CTO").val();
var row = cntrl.parentNode.parentNode;
var rowIndex = row.rowIndex - 1;
row.cells[1].getElementsByTagName("span")[0].innerHTML = usernames;
$("#overlayTasks").hide();
$("#dialogTasks").hide();
return false;
}
Instead of attaching your click handler like this:
$('#btnAddApprover').attr('onClick', 'if (!setApprovers(\'' +cntrl + '\')) return false;');
Try this instead:
$('#btnAddApprover').on('click', function() {
setApprovers(cntrl);
});
If you need to remove previously added event listeners, you can do that with:
$('#btnAddApprover').off('click');
Or if you want to attach the listener to listen just one time in the first place, you can use:
$('#btnAddApprover').one('click', function() {
setApprovers(cntrl);
});
(with one instead of on). Hope this helps!
Instead of
$('#btnAddApprover').attr('onClick', 'if (!setApprovers(\'' +cntrl + '\')) return false;');
use
$('#btnAddApprover').click(function() {
return setApprovers(cntrl);
}

Jquery - prevent default action of <a> on first click, allow default action on second click

How would I prevent the default action of an <a> on the first click (in order so that a tooltip is shown), then on the second click have the user directed to the value of the href attribute set on the element?
HTML
<a id="second" href="https://www.test.com/" title="" class="customtooltip c_tool2" data-original-title="data del toolltip numero 2">tooltip</a>
Jquery
var t = $('.c_tool2'), b = $('a[href^="http');
b.click(function(e){
if(t.length > 0){
e.preventDefault();
t.tooltip('show');
} else {
// on second click direct user to value of href
}
});
Assuming there will be multiple elements, using a common counter will not work. You can use counter on individual element using data-* attribute
Also, the selector to select the anchors is incorrect.
var t = $('.c_tool2'),
b = $('a[href^="http"]'); // <-- Added "] to make it correct
b.click(function (e) {
// Get the counter for clicked element
var clickCount = parseInt($(this).data('count'), 10) || 0;
// If counter is zero i.e. for the first click
if (!clickCount) {
// Update the value of the counter
$(this).data('count', ++clickCount);
t.tooltip('show');
// Prevent the default action of the page redirection
e.preventDefault();
}
// Else, follow the default action
});
Try to make use of .data() instead of polluting the global scope with counters,
b.click(function(e) {
if(!$(this).data("flag")) {
e.preventDefault();
$(this).data("flag",true);
t.tooltip('show');
} else {
// on second click direct user to value of href
}
});

How to disable the click if a function is in active status

I have created a fiddle of my function here( http://jsfiddle.net/rhy5K/10/ ) . Now i want to disable the button click i.e play/pause if the sound is playing like Get ready,5,4,3,2,1 .
I know only how to disable the form submit button , but I am very confused how to disable the click in my case the hyperlinks.
Explanation using code example:
I want to disable this
PLAY
click, while interpreter is executing the below code:
var playGetReady = function (done) {
var ids = ['audiosource', 'a_5', 'a_4', 'a_3', 'a_2', 'a_1'],
playNext = function () {
var id = ids.shift();
document.getElementById(id).play();
if (ids.length) {
setTimeout(playNext, 1000);
} else {
done();
}
};
playNext();
};
Warning: This JS fiddle demo may play sound on load
You may try this (Changes in following function), but not sure if this is you want and maybe there are other ways to do it.
App.prototype.start = function () {
var self = this;
// unbind for a while
self.$button.unbind('click', self.buttonHandler); // <--
var start = function () {
// start countdown
self.intervalHandle = setInterval($.proxy(self.tick, self), 1000);
// bind again
self.$button.click($.proxy(self.buttonHandler, self)); // <--
// change button text to PAUSE
self.$button.text('PAUSE');
};
if (this.newTimer) {
playGetReady(start);
} else {
start();
}
};
DEMO.
In jquery, it can be done easily by cancel default action. Here's the sample.
$("#btn_start").click(function(event){
if(not_active_flag){
// Prevent anchor to active
return false;
}else{
// Anchor active as usual
return true;
}
});
In your case, the link will ultimately call this.buttonHandler, which has the following code:
App.prototype.buttonHandler = function (e) {
e.preventDefault(); // prevent anchor default action
this.toggle(); // toggle play/pause
};
Because buttonHandler is attached before playGetReady is executed, it is not possible to let playGetReady attach a click handler to that anchor element that uses .stopImmediatePropagation() to prevent the other click handler from executing.
In this case #gp.'s solution in the comments is most likely the best solution. In your case you might even be able to use a local variable in your app. If you use a global variable, reference it with window.yourglobalvariable. If you use a local variable, make sure you define it somewhere and reference it with this.yourvariable. Change your buttonHandler to:
App.prototype.buttonHandler = function (e) {
e.preventDefault(); // prevent anchor default action
if( this.soundready )
this.toggle(); // toggle play/pause
};
On the appropiate place make this variable false to prevent the 'button' from working. When the button should work, change the variable to true. I think that should be just before done() in the code you have in your question, but you probably have a better idea in what order the code is executed.

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;
});
});

Categories

Resources