Toggle between two functions - javascript

Currently I have a button which changes its text from Pause to Resume when clicking on it. I use jQuery and toggle for this:
$(document).ready(function() {
$("#pause").click(function() {
$("td").toggle();
$(this).html($(this).html() == "Pause" ? "Resume" : "Pause");
});
});
This all works. I also have 2 functions:
function pauseTimer()
function startTimer()
How do I "integrate" these two functions into my toggle code? So when I hit Pause it will toggle the text to Resume AND also use the function pauseTimer() and if I hit the button again, the text will change back to Pause and also use StartTimer()?
Thanks

$(this).html() == "Pause" ? pauseTimer() : startTimer();
Will work. You have to change the html content of the element to Start or Pause in the functions so that the function will run alternatively according to the html of the element.

Unless I completely misinterpreted your question this should do it:
$("#pause").click(function() {
$("td").toggle();
if($(this).html() == "Pause")
{
$(this).html("Resume");
pauseTimer();
}else{
$(this).html("Pause");
startTimer();
}
});

Something like this ?
var doStuff = function(callback, text){
callback();
return text;
}
$(this).html($(this).html() == "Pause" ? doStuff(startTimer, "Resume") : doStuff(StartTimer, "Pause"));

var globalTimerPaused = false;
$(document).ready(function() {
$("#pause").click(function() {
$("td").toggle();
$(this).html($(this).html() == "Pause" ? "Resume" : "Pause");
if(!globalTimerPaused){ pauseTimer() } else { startTimer() };
globalTimerPaused = !globalTimerPaused;
});
});

Try this
$('selector').click(function () { // on click event
var song = $('theaudiotag');
if(song.paused) { // if song is paused
$(this).play(); // play it
$(this).html('Pause'); // change text
} else { // otherwise
$(this).pause(); // pause it
$(this).html('Play'); // change text
}
}
This uses jQuery API to check for the current status of the audio tag, and then toggle its state to play or pause and at the same time. It will work cross-browser.

You can use the window method here like:
$("#pause").click(function () {
$("td").toggle();
$(this).html($(this).html() == "Pause" ? "Resume" : "Pause");
window[$(this).html() === "Resume" ? "pauseTimer" : "startTimer"]();
});

You can use the jQuery is visible method:
if ($('td').is(":visible"))
{
pauseTimer();
}
else
{
startTimer()
}
Dan

Another option would be to do the following.
//jQuery 1.8 toggle replacement
$.fn.toggleClick = function(){
var methods = arguments,
count = methods.length;
return this.each(function(i, item){
var index = 0;
$(item).click(function(){
return methods[index++ % count].apply(this,arguments);
});
});
};
function startTime() {
$("td").toggle();
$(this).val("Start");
}
function pauseTime() {
$("td").toggle();
$(this).val("Pause");
}
$("#clickme").toggleClick(startTime,pauseTime);
JSFiddle

$(document).ready(function() {
$("#pause").click(function(pauseTimer(),StartTimer()) {
$("td").toggle();
$(this).html($(this).html() == "Pause" ? "Resume" : "Pause");
});
});

Related

function toggle - open all items

guys
I have a following HTML code with wrap (notice-wrap):
<div class="notice-title">
Title
</div>
<div class="notice-content">
Content text
</div>
<div class="notice-toggle" value="Hide" onclick="toggle()">
<img src="../img/icon_rollout.png">
</div>
And Toggle Script
function toggle() {
var newStatus = $('.notice-toggle').val() === "Hide" ? "Show" : "Hide";
$('.notice-toggle').val(newStatus);
if (newStatus == "Show") {
$("div.notice-content").css('overflow','hidden');
$("div.notice-content").css('height','80px');
$("div.notice-wrap").css('height','187px');
}
else {
$("div.notice-content").css('overflow','visible');
$("div.notice-content").css('height','100%');
$("div.notice-wrap").css('height','100%');
}
}
When i'm clicking on the toggle, open once all the items. How to make the opening only that element which i choose?
P.S. I also use Angular
Thanks in advance!
Maybe you can just change this:
function toggle() {
var newStatus = $('.notice-toggle').val() === "Hide" ? "Show" : "Hide";
$('.notice-toggle').val(newStatus);
if (newStatus == "Show") {
$("div.notice-content").css('overflow','hidden');
$("div.notice-content").css('height','80px');
$("div.notice-wrap").css('height','187px');
}
else {
$("div.notice-content").css('overflow','visible');
$("div.notice-content").css('height','100%');
$("div.notice-wrap").css('height','100%');
}
}
to:
function toggle() {
var noticeToggleElement = $(this);
var newStatus = noticeToggleElement.val() === "Hide" ? "Show" : "Hide";
noticeToggleElement.val(newStatus);
if (newStatus == "Show") {
noticeToggleElement.css('overflow','hidden');
noticeToggleElement.css('height','80px');
$("div.notice-wrap").css('height','187px');
}
else {
noticeToggleElement.css('overflow','visible');
noticeToggleElement.css('height','100%');
$("div.notice-wrap").css('height','100%');
}
}
As you should have the context of the element you toggle on with the mouse click.
As you're using jQuery, should be better if you remove the onclick from the HTML tag and make the bind in your javascript code, on a function that is executed on document ready:
$(function(){
$('div.notice-content').click(toggle);
})
But this is just a plus.
What you should do first is move that styling from js to css,
and have additional variations of your classes, for example:
.notice-title--toggled {
...
}
.notice-content--toggled {
...
}
.notice-toggle--toggled {
...
}
Now you have good separation of concerns, and your toggle function could just toggle classes for those elements.
Also you should put this toggle click handler on document ready, so final result would be:
$(function) {
$('.notice-toggle').click(function() {
$('.notice-title').toggleClass('notice-title--toggled');
$('.notice-content').toggleClass('notice-content--toggled');
$('.notice-toggle').toggleClass('notice-toggle--toggled');
});
}

firing the second .click function

I think this is very newbie question but is it possible to have 2 separate function on a .click on 1st and 2nd click?
$(div).click(function(){
alert("1st click");
},
function(){
alert("2nd click");
});
http://jsfiddle.net/2xe8a/
Or is there any suggestion that would separate that function?
Thanks guys!
Sure, just set something when clicked the first time and check it the second time
$('div').click(function(){
var clicked = $(this).data('clicked');
if ( clicked ) {
alert('the rest of the time');
}else{
alert('first time');
}
$(this).data('clicked', !clicked);
});
FIDDLE
One way would be to unbind on the first click:
function click1 () {
alert('1st click');
$(this).off('click', click1).on('click', click2);
}
function click2 () {
alert('2nd click');
}
$(function () {
$('#click').on('click', click1);
});
Updated JSFiddle: http://jsfiddle.net/2xe8a/1/
Another option would be to use a wrapper method to determine which method is supposed to fire:
function click1 () {
alert('1st click');
}
function click2 () {
alert('2nd click');
}
$(function () {
$('#click').data('clicks', 0).on('click', function () {
var $this = $(this),
clicks = $this.data('clicks') + 1;
switch (clicks) {
case 1: click1.call(this); break;
case 2: click2.call(this); break;
}
$this.data('clicks', clicks);
});
});
Updated JSFiddle: http://jsfiddle.net/2xe8a/6/
Edit: As per Juhana's suggestion, a 3rd option might look like this:
function click2 () {
alert('2nd click');
}
$(function () {
$('#click').one('click', function () {
alert('1st click');
$(this).one('click', click2);
});
});
JSFiddle Link: http://jsfiddle.net/2xe8a/8/
If you only want each function to happen once, you can use one instead of on (and, I always use something like on('click') instead of the shortcut click() method):
$("#click").one('click', function(){
alert("1st click");
$("#click").one('click', function(){
alert("2nd click");
});
});
If you need a little more control over which one fires, you can use on and then off to unbind the event handlers:
$("#click").on('click', function(){
alert("1st click");
$("#click").off('click');
$("#click").on('click', function(){
alert("2nd click");
$("#click").off('click');
});
});
If you want to do it with variables, you could do:
var firstClick = true;
$("#click").on('click', function(){
if (firstClick) {
alert("1st click");
firstClick = false;
}
else {
alert("2nd click");
}
});
I am unsure of what exactly you are trying to do.
If you are trying to have the 2nd function execute every 2nd click (i.e even number of clicks), and execute the 1st function on the odd number of clicks, then why not use a counter?
This is a very simple example but I think it illustrates the principle:
var count = 0;
$("#click").click(function(){
if (count % 2 === 0) {
oddNumberOfClicks();
}
else {
evenNumberOfClicks();
}
count++;
});
function oddNumberOfClicks() {
alert('Doing some work for odd');
}
function evenNumberOfClicks() {
alert('Doing some work for even');
}
http://jsfiddle.net/2xe8a/4/
Using an incrementing variable?
clicks = 0;
$(div).click(function(){
clicks = clicks +1; // clicks++
if ( clicks == 1 ) {
alert("1st click");
} else if ( clicks == 2 ) {
alert("2nd click");
} else {
//...
}
});
(function(){
var count = 0;
$("#click").click(function(e){
if(count % 2 == 0){
count++;
alert(1);
// first click
}else{
count++;
alert(2);
// second click
}
});
});
Using a counter.
FIDDLE
P.S. This thing can be done without jQuery. http://youmightnotneedjquery.com/
Simple way:
var t = false;
$("#click").click(
function(){
if(!t){
alert("1st click");
t = true;
} else {
alert("2st click");
}
}
);
Fiddle:
http://jsfiddle.net/2xe8a/9/
By 2nd click do you mean a double click? If so, there is a double click method in jQuery:
$(div).dblclick( function() {
alert("asdf");
});

Stop single click event when double-clicking? [duplicate]

Is there something in jquery that would allow me to differentiate between behavior on double click and single click?
When I bind both to same element only the single click gets executed.
Is there a way that wait for some time before execution of the single click to see if the user clicks again or not?
Thanks :)
I found that John Strickler's answer did not quite do what I was expecting. Once the alert is triggered by a second click within the two-second window, every subsequent click triggers another alert until you wait two seconds before clicking again. So with John's code, a triple click acts as two double clicks where I would expect it to act like a double click followed by a single click.
I have reworked his solution to function in this way and to flow in a way my mind can better comprehend. I dropped the delay down from 2000 to 700 to better simulate what I would feel to be a normal sensitivity. Here's the fiddle: http://jsfiddle.net/KpCwN/4/.
Thanks for the foundation, John. I hope this alternate version is useful to others.
var DELAY = 700, clicks = 0, timer = null;
$(function(){
$("a").on("click", function(e){
clicks++; //count clicks
if(clicks === 1) {
timer = setTimeout(function() {
alert("Single Click"); //perform single-click action
clicks = 0; //after action performed, reset counter
}, DELAY);
} else {
clearTimeout(timer); //prevent single-click action
alert("Double Click"); //perform double-click action
clicks = 0; //after action performed, reset counter
}
})
.on("dblclick", function(e){
e.preventDefault(); //cancel system double-click event
});
});
The solution given from "Nott Responding" seems to fire both events, click and dblclick when doubleclicked. However I think it points in the right direction.
I did a small change, this is the result :
$("#clickMe").click(function (e) {
var $this = $(this);
if ($this.hasClass('clicked')){
$this.removeClass('clicked');
alert("Double click");
//here is your code for double click
}else{
$this.addClass('clicked');
setTimeout(function() {
if ($this.hasClass('clicked')){
$this.removeClass('clicked');
alert("Just one click!");
//your code for single click
}
}, 500);
}
});
Try it
http://jsfiddle.net/calterras/xmmo3esg/
Sure, bind two handlers, one to click and the other to dblclick. Create a variable that increments on every click. then resets after a set delay. Inside the setTimeout function you can do something...
var DELAY = 2000,
clicks = 0,
timer = null;
$('a').bind({
click: function(e) {
clearTimeout(timer);
timer = setTimeout(function() {
clicks = 0;
}, DELAY);
if(clicks === 1) {
alert(clicks);
//do something here
clicks = 0;
}
//Increment clicks
clicks++;
},
dblclick: function(e) {
e.preventDefault(); //don't do anything
}
});
You could probably write your own custom implementation of click/dblclick to have it wait for an extra click. I don't see anything in the core jQuery functions that would help you achieve this.
Quote from .dblclick() at the jQuery site
It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable.
Look at the following code
$("#clickMe").click(function (e) {
var $this = $(this);
if ($this.hasClass('clicked')){
alert("Double click");
//here is your code for double click
return;
}else{
$this.addClass('clicked');
//your code for single click
setTimeout(function() {
$this.removeClass('clicked'); },500);
}//end of else
});
Demo goes here http://jsfiddle.net/cB484/
I've written a jQuery plugin that allow also to delegate the click and dblclick events
// jQuery plugin to bind both single and double click to objects
// parameter 'delegateSelector' is optional and allow to delegate the events
// parameter 'dblclickWait' is optional default is 300
(function($) {
$.fn.multipleClicks = function(delegateSelector, clickFun, dblclickFun, dblclickWait) {
var obj;
if (typeof(delegateSelector)==='function' && typeof(clickFun)==='function') {
dblclickWait = dblclickFun; dblclickFun = clickFun; clickFun = delegateSelector; delegateSelector = null; // If 'delegateSelector' is missing reorder arguments
} else if (!(typeof(delegateSelector)==='string' && typeof(clickFun)==='function' && typeof(dblclickFun)==='function')) {
return false;
}
return $(this).each(function() {
$(this).on('click', delegateSelector, function(event) {
var self = this;
clicks = ($(self).data('clicks') || 0)+1;
$(self).data('clicks', clicks);
if (clicks == 1) {
setTimeout(function(){
if ($(self).data('clicks') == 1) {
clickFun.call(self, event); // Single click action
} else {
dblclickFun.call(self, event); // Double click action
}
$(self).data('clicks', 0);
}, dblclickWait || 300);
}
});
});
};
})(jQuery);
This solution works for me
var DELAY = 250, clicks = 0, timer = null;
$(".fc-event").click(function(e) {
if (timer == null) {
timer = setTimeout(function() {
clicks = 0;
timer = null;
// single click code
}, DELAY);
}
if(clicks === 1) {
clearTimeout(timer);
timer = null;
clicks = -1;
// double click code
}
clicks++;
});
i am implementing this simple solution , http://jsfiddle.net/533135/VHkLR/5/
html code
<p>Click on this paragraph.</p>
<b> </b>
script code
var dbclick=false;
$("p").click(function(){
setTimeout(function(){
if(dbclick ==false){
$("b").html("clicked")
}
},200)
}).dblclick(function(){
dbclick = true
$("b").html("dbclicked")
setTimeout(function(){
dbclick = false
},300)
});
its not much laggy
var singleClickTimer = 0; //define a var to hold timer event in parent scope
jqueryElem.click(function(e){ //using jquery click handler
if (e.detail == 1) { //ensure this is the first click
singleClickTimer = setTimeout(function(){ //create a timer
alert('single'); //run your single click code
},250); //250 or 1/4th second is about right
}
});
jqueryElem.dblclick(function(e){ //using jquery dblclick handler
clearTimeout(singleClickTimer); //cancel the single click
alert('double'); //run your double click code
});
I made some changes to the above answers here which still works great: http://jsfiddle.net/arondraper/R8cDR/
Below is my simple approach to the issue.
JQuery function:
jQuery.fn.trackClicks = function () {
if ($(this).attr("data-clicks") === undefined) $(this).attr("data-clicks", 0);
var timer;
$(this).click(function () {
$(this).attr("data-clicks", parseInt($(this).attr("data-clicks")) + 1);
if (timer) clearTimeout(timer);
var item = $(this);
timer = setTimeout(function() {
item.attr("data-clicks", 0);
}, 1000);
});
}
Implementation:
$(function () {
$("a").trackClicks();
$("a").click(function () {
if ($(this).attr("data-clicks") === "2") {
// Double clicked
}
});
});
Inspect the clicked element in Firefox/Chrome to see data-clicks go up and down as you click, adjust time (1000) to suit.
(function($){
$.click2 = function (elm, o){
this.ao = o;
var DELAY = 700, clicks = 0;
var timer = null;
var self = this;
$(elm).on('click', function(e){
clicks++;
if(clicks === 1){
timer = setTimeout(function(){
self.ao.click(e);
}, DELAY);
} else {
clearTimeout(timer);
self.ao.dblclick(e);
}
}).on('dblclick', function(e){
e.preventDefault();
});
};
$.click2.defaults = { click: function(e){}, dblclick: function(e){} };
$.fn.click2 = function(o){
o = $.extend({},$.click2.defaults, o);
this.each(function(){ new $.click2(this, o); });
return this;
};
})(jQuery);
And finally we use as.
$("a").click2({
click : function(e){
var cid = $(this).data('cid');
console.log("Click : "+cid);
},
dblclick : function(e){
var cid = $(this).data('cid');
console.log("Double Click : "+cid);
}
});
Same as the above answer but allows for triple click. (Delay 500)
http://jsfiddle.net/luenwarneke/rV78Y/1/
var DELAY = 500,
clicks = 0,
timer = null;
$(document).ready(function() {
$("a")
.on("click", function(e){
clicks++; //count clicks
timer = setTimeout(function() {
if(clicks === 1) {
alert('Single Click'); //perform single-click action
} else if(clicks === 2) {
alert('Double Click'); //perform single-click action
} else if(clicks >= 3) {
alert('Triple Click'); //perform Triple-click action
}
clearTimeout(timer);
clicks = 0; //after action performed, reset counter
}, DELAY);
})
.on("dblclick", function(e){
e.preventDefault(); //cancel system double-click event
});
});
This is a method you can do using the basic JavaScript, which is works for me:
var v_Result;
function OneClick() {
v_Result = false;
window.setTimeout(OneClick_Nei, 500)
function OneClick_Nei() {
if (v_Result != false) return;
alert("single click");
}
}
function TwoClick() {
v_Result = true;
alert("double click");
}
If you don't want to create separate variables to manage the state, you can check this answer https://stackoverflow.com/a/65620562/4437468

How can I toggle a onclick="function" for a button

I have a button that plays and stops a video. How can I toggle between the .play() and .pause() efficiently?
<button id="thebutton" onclick="BV.getPlayer().play();"></button>
First off, I would suggest not using inline event handlers. If you're using jQuery, then I suggest you use that.
After each click, set a variable to tell whether it's playing or not, then trigger the correct action.
$(function(){
$('#thebutton').click(function(){
var isPlaying = $(this).data('isplaying');
if(isPlaying){
BV.getPlayer().pause();
}
else{
BV.getPlayer().play();
}
$(this).data('isplaying', !isPlaying);
});
});
jQuery used to have a .toggle() "event", but it was removed.
Add a class that acts as check for the player status. And then use this code.
$("#theButton").click(function() {
if($(this).hasClass('playing')) {
BV.getPlayer().pause();
} else {
BV.getPlayer().play();
}
$(this).toggleClass('playing')
})
$('#thebutton').click(function() {
if ($(this).val() == "play") {
$(this).val("pause");
play_int();
}
else {
$(this).val("play");
play_pause();
}
});
or
$(function(){
$('#play').click(function() {
// if the play button value is 'play', call the play function
// otherwise call the pause function
$(this).val() == "play" ? play_int() : play_pause();
});
});
function play_int() {
$('#play').val("pause");
// do play
}
function play_pause() {
$('#play').val("play");
// do pause
}
aka
jquery toggle button value
var isPlaying = false;
var player = BV.getPlayer();
$("#thebutton").click(function() {
if (isPlaying) {
player.pause();
isPlaying = false;
} else {
player.play();
isPlaying = true;
}
});

JavaScript - jQuery toggle option

I have a script to execute some tasks based on an option variable. Option has a default value 1. The value can be toggled by clicking some links. Then a set of operations are set, for that operations to execute. The sample layout will be like;
HTML
<a id="opt1">1</a><br><a id="opt2">2</a><br><a id="opt3">3</a><br>
<div id="mydiv">option1</div>
JS
var opt=1;
$('#opt1').click(function() {
opt=1;
});
$('#opt2').click(function() {
opt=2;
});
$('#opt3').click(function() {
opt=3;
});
if(opt == 1){
$('#mydiv').text("option1");
}else if(opt == 2){
$('#mydiv').text("option2");
}else{
$('#mydiv').text("option3");
}
JS is wrapped inside document ready function. The sample is meant to change text according to option variable. Sorry that the tasks cannot be nested inside .click(function() and are purely depend on option value. How can I achieve this?
here is the fiddle http://jsfiddle.net/Naw3y/
problem is your if condition is called just once on document.ready.. make a function , add your condition and call that function in click event
var opt=1;
$('#opt1').click(function() {
opt=1;
divText(opt); //calling divText(1) is shorter :)
});
$('#opt2').click(function() {
opt=2;
divText(opt)
});
$('#opt3').click(function() {
opt=3;
divText(opt)
});
function divText(opt){
if(opt == 1){
$('#mydiv').text("option1");
}else if(opt == 2){
$('#mydiv').text("option2");
}else{
$('#mydiv').text("option3");
}
}
not sure why aren't you calling straight away .. without if and function.. but here you go
$('#opt1').click(function() {
$('#mydiv').text("option1");
});
$('#opt2').click(function() {
$('#mydiv').text("option2");
});
$('#opt3').click(function() {
$('#mydiv').text("option3");
});
fiddle here
fiddle for second option
This should do the trick: http://jsfiddle.net/Naw3y/6/:
var opt = 1;
$(function() {
$('#opt1').click(function() {
opt=1;
changeText();
});
$('#opt2').click(function() {
opt=2;
changeText();
});
$('#opt3').click(function() {
opt=3;
changeText();
});
});
function changeText(){
if(opt == 1){
$('#mydiv').text("option1");
}else if(opt == 2){
$('#mydiv').text("option2");
}else{
$('#mydiv').text("option3");
}
}
I think what you need in your situation is 'encapsulation' of your property, and this is what the other answers lack:
var opt;
//setter function for opt that does the div update
function setOpt(value) {
opt = value;
$('#mydiv').text('option' + value);
}
$(document).ready(function() {
//bind click handlers
$('#opt1').click(function() {
setOpt(1);
});
$('#opt2').click(function() {
setOpt(2);
});
$('#opt3').click(function() {
setOpt(3);
});
//set default value
setOpt(1);
});
$(document).ready(function(){
$('a').click(function(){
$('#mydiv').text('option'+$(this).html());
});
});
Sorry If i didnt understand your question well.. try to explain better..

Categories