2 anchor with one click - javascript

So here is my code
prev
prev
How do I make it both click if I click any of it ?
If I click .slider-1-prev, at the same I click .slider-2-prev
If I click .slider-2-prev, at the same I click .slider-2-prev
How to make it by javascript ?

As well as triggering the event on the other link, you need to shield against infinite repeating (e.g. with a shield variable):
var inClick = false;
$(document).ready(function {
$('.slider-1-prev').on('click', function {
if (!inClick) {
inClick = true;
$('.slider-2-prev').trigger('click');
inClick = false;
}
});
$('.slider-2-prev').on('click', function {
if (!inClick) {
inClick = true;
$('.slider-1-prev').trigger('click');
inClick = false;
}
});
})
If you want a shorter version, you can listen for both on one handler and click "the other":
var inClick = false;
$(document).ready(function {
var $sliders = $('.slider-1-prev,.slider-2-prev');
$sliders.on('click', function {
if (!inClick) {
inClick = true;
// Click the one that was not clicked (not this)
$sliders.not(this).trigger('click');
inClick = false;
}
});
})
Another option is a bit more complicated as you need to turn the handler off and then on again. Stick with this simple one for now.
The on/off approach involves disabling the handling while executing it, so that it will not trigger again until you reconnect it. The downside is you need to reference a separate function so that it can effectively reference itself:
$(document).ready(function {
var $sliders = $('.slider-1-prev,.slider-2-prev');
// Define separate named function
var clickTheOtherOne = function(){
// Disable the click
$sliders.off('click');
// Click the one that was not clicked (not this)
$sliders.not(this).trigger('click');
// Reenable the click handler
$sliders.on('click', clickTheOtherOne);
}
// Initial enabling of the handler
$sliders.on('click', clickTheOtherOne);
});

If they're going to behave the same, why not define only one function for both?
$('.slider-1-prev, .slider-2-prev').click(function(){
//... mutual code
});

I can't figure why you need to do what you ask, but try this approach:
js code:
// this will work on all classes that start with 'slider-prev'
$('*[class^="slider-prev"]').on('click',function{
// do something
});
Of course you will need to alter your htm code to:
prev
prev

this should do the trick
$(document).ready(function{
$('.slider-1-prev').on('click',function{
$('.slider-2-prev').trigger('click');
});
$('.slider-2-prev').on('click',function{
$('.slider-1-prev').trigger('click');
});
})

Try this -
$('.slider-1-prev').click(function(){
$('.slider-2-prev').trigger('click');
});
// If you need the opposite, then do -
$('.slider-2-prev').click(function(){
$('.slider-1-prev').trigger('click');
});

Related

Kendo toolbar button not firing click event after being enabled

This is my logic, here I am trying to disable the save changes button and prevent click event on it if the user enters a duplicate value and enable it again if the user changes the values but after enabling it the update / save event does not occur am I doing something wrong? This is my code
function OnChange(data) {
//data.preventDefault();
$(".k-grid-save-changes")
.attr("role", "button")
.removeClass("k-state-disabled")
//.addClass("k-grid-save-changes")
.click(function () {
return true;
});
//console.log("data", data.items["0"].ProviderTypeName);
var name = data.items["0"].ProviderTypeName;
var Id = data.items["0"].Id;
var grid = $("#grid").data("kendoGrid");
//console.log("Grid ", grid);
grid.tbody.find('>tr').each(
function () {
$(this).css('background', 'white');
var dataItem = grid.dataItem(this);
//console.log(dataItem.ProviderTypeName)
if (dataItem.ProviderTypeName == name && dataItem.Id != Id) {
$(this).css('background', 'red');
$(".k-grid-save-changes")
//.removeClass("k-grid-save-changes")
.addClass("k-state-disabled")
//.removeAttr("role")
.click(function () {
return false;
});
}
});
}
This is where is call the on change event
.Events(events => events.RequestStart("OnRequestStart").Change("OnChange").RequestEnd("OnRequestEnd").Error("onError"))
If I remove the "return false;" it is working as expected but this allows duplicated values to be saved. So I have used this.
If I understand correctly in your code you do exactly what you mention as a problem. At every change you disable the save functionality with the return false. You don't enable it again at any point.
If you add an event handler to the button then you have to undo it at a later point. Since though I don't believe that the validation should occur at the change event but at the button click I would suggest to use the grid Save event where you could iterate dataSource.data() of your grid (much better) do your check and if anything happens return false.
One other way to go since you probably want the css effect with the background is to keep your code and discard the click event. Just set a flag that you could use in the save event. Something like this:
if(// your control){
$(this).css('background', 'red');
duplicatedValue = true;
}else{
.removeClass("k-grid-save-changes");
duplicatedValue = false;
}
And in the save event
function onSave(){
if(duplicatedValue){
return false;
}
}

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

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 .load() How to prevent double loading from double clicking

I am using jQuery load() function to load some pages into container. Here is the code:
$('div.next a').live('click',function() {
$('.content').load('page/3/ #info','',function(){
//do something
});
return false;
});
Everything works just fine but the problem is when I quickly double click the div.next link, from console I see that it loads the page twice because I did a quick double click. I could even make it 3 clicks and it will load it 3 times and show in console smth like that:
GET http://site/page/3/ 200 OK 270ms
GET http://site/page/3/ 200 OK 260ms
My question is how to prevent such double clicking and not to let load the target page more then once no matter how many times it was clicked.
Thank you.
Whatever happened to good ol' JavaScript? Why are you all trying to figure it out with pure jQuery?
var hasBeenClicked = false;
$('div.next a').live('click',function() {
if(!hasBeenClicked){
hasBeenClicked = true;
$('.content').load('page/3/ #info','',function(){
//do something
//If you want it clickable AFTER it loads just uncomment the next line
//hasBeenClicked = false;
});
}
return false;
});
As a side note, never never never use .live(). Use .delegate instead like:
var hasBeenClicked = false;
$('div.next').delegate('a','click',function() {
if(!hasBeenClicked){
hasBeenClicked = true;
$('.content').load('page/3/ #info','',function(){
//do something
//If you want it clickable AFTER it loads just uncomment the next line
//hasBeenClicked = false;
});
}
return false;
});
Why? Paul Irish explains: http://paulirish.com/2010/on-jquery-live/
To answer your comment...
This could happen if you have your delegate function nested inside your AJAX call (.load(), .get(), etc). The div.next has to be on the page for this to work. If div.next isn't on the page, and this isn't nested, just do this:
$('#wrapper').delegate('div.next a','click',function() {
http://api.jquery.com/delegate/
Delegate needs the selector to be the parent of the dynamically added element. Then, the first parameter of delegate (div.next a in the last example) is the element to look for within the selected element (#wrapper). The wrapper could also be body if it's not wrapped in any element.
You could try using the jquery one method:
$("a.button").one("click", function() {
$('.content').load('page/3/ #info','',function(){
//do something
});
});
You could unbind the click event with die():
$(this).die('click').click(function() { return False; });
Or you could give the element a .clicked class once it is clicked:
$(this).addClass('clicked');
And check if that class exists when performing your logic:
$('div.next a').live('click',function() {
if (!$(this).is('.clicked')) {
$(this).addClass('clicked');
$('.content').load('page/3/ #info','',function(){
//do something
});
}
return false;
});
Store whether you're waiting for the load in a variable.
(function() {
var waitingToLoad = false;
$('div.next a').live('click',function() {
if (!waitingToLoad) {
waitingToLoad = true;
$('.content').load('page/3/ #info','',function(){
waitingToLoad = false;
//do something
});
}
return false;
});
})()

Prevent click event in jQuery triggering multiple times

I have created a jQuery content switcher. Generally, it works fine, but there is one problem with it. If you click the links on the side multiple times, multiple pieces of content sometimes become visible.
The problem most likely lies somewhere within the click event. Here is the code:
$('#tab-list li a').click(
function() {
var targetTab = $(this).attr('href');
if ($(targetTab).is(':hidden')) {
$('#tab-list li').removeClass('selected');
var targetTabLink = $(this).parents('li').eq(0);
$(targetTabLink).addClass('selected');
$('.tab:visible').fadeOut('slow',
function() {
$(targetTab).fadeIn('slow');
}
);
}
return false;
}
);
I have tried adding a lock to the transition so that further clicks are ignored as the transition is happening, but to no avail. I have also tried to prevent the transition from being triggered if something is already animating, using the following:
if ($(':animated')) {
// Don't do anything
}
else {
// Do transition
}
But it seems to always think things are being animated. Any ideas how I can prevent the animation being triggered multiple times?
One idea would be to remove the click event at the start of your function, and then add the click event back in when your animation has finished, so clicks during the duration would have no effect.
If you have the ability to execute code when the animation has finished this should work.
Add a variable to use as a lock rather than is(:animating).
On the click, check if the lock is set. If not, set the lock, start the process, then release the lock when the fadeIn finishes.
var blockAnimation = false;
$('#tab-list li a').click(
function() {
if(blockAnimation != true){
blockAnimation = true;
var targetTab = $(this).attr('href');
if ($(targetTab).is(':hidden')) {
$('#tab-list li').removeClass('selected');
var targetTabLink = $(this).parents('li').eq(0);
$(targetTabLink).addClass('selected');
$('.tab:visible').fadeOut('slow',
function() {
$(targetTab).fadeIn('slow', function(){ blockAnimation=false; });
}
);
}
}
return false;
}
);
Well this is how i did it, and it worked fine.
$(document).ready(function() {
$(".clickitey").click(function () {
if($("#mdpane:animated").length == 0) {
$("#mdpane").slideToggle("slow");
$(".jcrtarrow").toggleClass("arrow-open");
}
});
});
this is not doing what your code does ofcourse this is a code from my site, but i just like to point how i ignored the clicks that were happening during the animation. Please let me know if this is inefficient in anyway. Thank you.
I toyed around with the code earlier and came up with the following modification which seems to work:
$('#tab-list li a').click(
function() {
$('.tab:animated').stop(true, true);
var targetTab = $(this).attr('href');
if ($(targetTab).is(':hidden')) {
$('#tab-list li').removeClass('selected');
var targetTabLink = $(this).parents('li').eq(0);
$(targetTabLink).addClass('selected');
$('.tab:visible').fadeOut('slow',
function() {
$(targetTab).fadeIn('slow');
}
);
}
return false;
}
);
All that happens is, when a new tab is clicked, it immediately brings the current animation to the end and then begins the new transition.
one way would be this:
$('#tab-list ul li').one( 'click', loadPage );
var loadPage = function(event) {
var $this = $(this);
$global_just_clicked = $this;
var urlToLoad = $this.attr('href');
$('#content-area').load( urlToLoad, pageLoaded );
}
$global_just_clicked = null;
var pageLoaded() {
$global_just_clicked.one( 'click', loadPage );
}
As you can see, this method is fraught with shortcomings: what happens when another tab is clicked before the current page loads? What if the request is denied? what if its a full moon?
The answer is: this method is just a rudimentary demonstration. A proper implementation would:
not contain the global variable $global_just_clicked
not rely on .load(). Would use .ajax(), and handle request cancellation, clicking of other tabs etc.
NOTE: In most cases you need not take this round-about approach. I'm sure you can remedy you code in such a way that multiple clicks to the same tab would not affect the end result.
jrh.
One way to do this to use timeStamp property of event like this to gap some time between multiple clicks:
var a = $("a"),
stopClick = 0;
a.on("click", function(e) {
if(e.timeStamp - stopClick > 300) { // give 300ms gap between clicks
// logic here
stopClick = e.timeStamp; // new timestamp given
}
});

Categories

Resources