OR condition for running function - javascript

I have button (".moreAlertsBtn") that run function when user click on it
I would like to run the same function if user click on another button that contain the id "#alertsBtn"
how do I add OR condition?
$(document).on('click','.moreAlertsBtn',function() { }
also - inside the function, can i add contision if user click on the first button and another if he click on the second?

Just separate them using comma(,) like this:
$(document).on('click','.moreAlertsBtn, #alertsBtn',function() { });
can i add condition if user click on the first button and another if
he click on the second?
$(document)
.on('click','.moreAlertsBtn, #alertsBtn',function() {
if($(this).hasClass('moreAlertsBtn')) {
//.moreAlertsBtn clicked
} else {
//#alertsBtn clicked
}
});

how do I add OR condition?
You can use the comma, which in CSS is "or" (but keep reading):
$(document).on('click','.moreAlertsBtn, #alertsBtn',function() { });
But:
also - inside the function, can i add contision if user click on the first button and another if he click on the second?
If you're going to do that, then it makes more sense to use separate handlers:
$(document).on('click','.moreAlertsBtn',function() { });
$(document).on('click','#alertsBtn',function() { });
But answering the question, yes, you can tell like this:
if (this.id === "alertsBtn") {
// It's #alertsBtn
} else {
// Must be .moreAlertsBtn
}
E.g.:
$(document).on('click','.moreAlertsBtn, #alertsBtn',function() {
if (this.id === "alertsBtn") {
// It's #alertsBtn
} else {
// Must be .moreAlertsBtn
}
});
That works because jQuery will call your handler with this referring to the DOM element you "hooked" the event on (even when you're actually doing delegation, as you are in your examples).

You can use comma in-between selectors as follows :
$(document).on('click','.moreAlertsBtn,#alertsBtn',function() { }

Related

What is the correct approach to use if in this situation?

I didn't find an answer that satisfies me about this newbie javascript (using jQuery) question...
I have these 2 codes inside a document ready...
CODE 1
$('myElement').click(function(){
if(isMobile()){
//do something...
}
});
CODE 2
if(isMobile()){
$('myElement').click(function(){
// do somthing...
});
}
What is the correct approach and why?
Thanks guys
The first one creates the click event in any case, and inside of it you do different stuff depending on the condition.
The second option only generates the click event if the condition is true.
So, it depends on the logic of your application. If the click event is only needed if isMobile()is true, I'll go with the second option, so you don't generate an event that you aren't going to need.
If you always need the click event, but it has to do different things depending of the isMobile() condition, then the first one is the way to go.
I hope it helps
Code 1
$('myElement').click(function() {
if(isMobile()) {
// do something...
}
});
The action is always attached to your element.
For each click on your element, it will test if you are on mobile.
Code 2
if(isMobile()) {
$('myElement').click(function() {
// do something...
});
}
It will test if you are on mobile first. If so, it will attach your action to your element. If not, you will never get the action when you click on your element.
Here an example :
const isMobile = false
if (isMobile) {
console.log("code 1 - isMobile")
$("#code1").click(function() {
console.log("code 1 - click")
})
}
$("#code1").click(function() {
console.log("code 2 - click")
if (isMobile) {
console.log("code 2 - isMobile")
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Code 1</h2>
<button id="code1">Click me !</button>
<h2>Code 2</h2>
<button id="code2">Click me !</button>

If statement only checks variable value once in javascript

I am trying to understand how javascript (jquery in this case) if statements work. I thought i understood but i don't fully get some things. Please see the code below. Why is it when i click on the element with the class of "cat" that it does not remove the class of "black" and add the class of "red".
$(function() {
var cat = true;
$( ".cat" ).click(function() {
cat = false;
});
if (cat === true) {
$('.cat').removeClass('red').addClass('black');
} else {
$('.cat').removeClass('black').addClass('red');
}
});
i know there is probably a very simple answer to this but i'm just learning so any help would be appreciated, thanks in advance.
Toggle the value of cat and put the if block inside the function that you want to bind with the event 'click':
$(".cat").click(function() {
cat = !cat;
if (cat === true) {
$('.cat').removeClass('red').addClass('black');
} else {
$('.cat').removeClass('black').addClass('red');
}
});
Edit: Simpler way to do this is to use .toggleClass():
$(".cat").click(function() {
$(this).toggleClass('red black');
});
If you want to check on click, put the if inside the click event. The reason why your solution doesn't work is because you attach a listener to the element, but you immediately do a check. The check doesn't happen every time the user clicks, just once. You must put it in the listener's callback function so it executes every time the element is clicked:
$(function() {
$(".cat").click(function() {
$(".cat").toggleClass("black red");
});
});
How this works is it attaches a click event to .cat and, on click, toggles the classes black and red. This completely gets rid of the checking because that isn't necessary. Just toggle the classes on click. Also, no need to repeat the selector, just use this. Here's a snippet:
$(function() {
$(".cat").click(function() {
$(this).toggleClass("black red");
});
});
.black {
color: black;
}
.red {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cat red">Test</div>
Your code is not removing class black and adding class red because your if(){}else{} code block running when your page is loading. When you are clicking the cat class it is only assigning the value of cat variable to false. since your if else code block is out of your click function that is why it is not executing again. and that is why it is not working. To work your code place your if else code block in the click function like this:
$( ".cat" ).click(function() {
cat = false;
if (cat === true) {
$('.cat').removeClass('red').addClass('black');
} else {
$('.cat').removeClass('black').addClass('red');
};
});

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

Change the value of button

In my html page I'm having one div element as subbutton. In javascript I'm appending button to this div element.
$.each(responseObj.me, function (i, me) {
$('#subbutton').append('<input type="button" value=subscribe id="subscribe" background-color="green" onclick="">'+'</input>');
var subscribe=check();
function check()
{
if(responseObj.me[i].isSubscribed==="false")
{
document.getElementById("subscribe").value="I Trust";
$('#subbutton').click(function() {
sub(text);
document.getElementById("subscribe").value="Trusted";
});
}
else
{
document.getElementById("subscribe").value="Trusted";
$('#subbutton').click(function() {
unsub(text);
document.getElementById("subscribe").value="I Trust";
});
}
}
But the problem is when I click on the button first time, it's able to subscribe if it's not subscribed and able to unsubscribe if it's already subscribed. But if again I want to subscribe who is unsubscribed then it's not unsubscribed.sub(text) is a function used to subscribe person and unsub(text) is a function to unsubscribe person.
you can use,
$(document).on("click",".subscribe",function(){
//your code here
});
i created a jsfiddle. just check it out whether that is your aim
http://jsfiddle.net/2dAf9/
is you are calling check method more than one time??
then instead of using $('#subbutton').click() you have to use $('#subbutton').unbind("click").bind("click",function(){});
because it will not clear the click event it first initialized. it will call both funcitons.
try this way

Registering jQuery click, first and second click

Is there a way to run two functions similar to this:
$('.myClass').click(
function() {
// First click
},
function() {
// Second click
}
);
I want to use a basic toggle event, but .toggle() has been deprecated.
Try this:
$('.myClass').click(function() {
var clicks = $(this).data('clicks');
if (clicks) {
// odd clicks
} else {
// even clicks
}
$(this).data("clicks", !clicks);
});
This is based on an already answered question: Alternative to jQuery's .toggle() method that supports eventData?
Or this :
var clicks = 0;
$('.myClass').click(function() {
if (clicks == 0){
// first click
} else{
// second click
}
++clicks;
});
this I worked for my menu
var SubMenuH = $('.subBoxHederMenu').height();
var clicks = 0;
$('.btn-menu').click(function(){
if(clicks == 0){
$('.headerMenu').animate({height:SubMenuH});
clicks++;
console.log("abierto");
}else{
$('.headerMenu').animate({height:"55px"});
clicks--;
console.log("cerrado");
}
console.log(clicks);
});
i don't know what you are tryin to do but we can get basic toggle by
$('.myClass').click({
var $this=$(this);
if($this.is(':hidden'))
{
$this.show('slow');
}else{
$this.hide('slow');
}
})
note: this works for endless click event for that element .. not just for two clicks (if that is what you want)
OR you can use css class to hide/show the div and use jquery.toggleClass()
In the method mentioned below We are passing an array of functions to our custom .toggleClick() function. And We are using data-* attribute of HTML5 to store index of the function that will be executed in next iteration of click event handling process. This value, stored in data-index property, is updated in each iteration so that we can track the index of function to be executed in next iteration.
All of these functions will be executed one by one in each iteration of click event. For example in first iteration function at index[0] will be executed, in 2nd iteration function stored at index[1] will be executed and so on.
You can pass only 2 functions to this array in your case. But this method is not limited to only 2 functions. You can pass 3, 4, 5 or more functions in this array and they will be executed without making any changes in code.
Example in the snippet below is handling four functions. You can pass functions according to your own needs.
$.fn.toggleClick = function(funcArray) {
return this.click(function() {
var elem = $(this);
var index = elem.data('index') || 0;
funcArray[index]();
elem.data('index', (index + 1) % funcArray.length);
});
};
$('.btn').toggleClick([
function() {
alert('From Function 1');
}, function() {
alert('From Function 2');
}, function() {
alert('From Function 3');
}, function() {
alert('From Function 4');
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button type="button" class="btn">Click Me</button>
<button type="button" class="btn">Click Me</button>
If you literally only want the first and second click:
$('.myClass').one( 'click', function() {
// First click
$('.myClass').one( 'click', function() {
// Second click
});
);
var click_s=0;
$('#show_pass').click(function(){
if(click_s % 2 == 0){
$('#pwd').attr('type','text');
$(this).html('Hide');
}
else{
$('#pwd').attr('type','password');
$(this).html('Show');
}
click_s++;
});
When You click the selector it automatically triggers second and waiting for another click event.
$(selector).click(function(e){
e.preventDefault(); // prevent from Posting or page loading
//do your stuff for first click;
$(this).click(function(e){
e.preventDefault();// prevent from Posting or page loading
// do your stuff for second click;
});
});
I hope this was helpful to you..
I reach here looking for some answers, and thanks to you guys I´ve solved this in great manner I would like to share mi solution.
I only use addClass, removeClass and hasClass JQuery commands.
This is how I´ve done it and it works great:
$('.toggle').click(function() {
if($('.categ').hasClass("open")){
$('.categ').removeClass('open');
}
else{
$('.categ').addClass('open');
}
});
This way a class .open is added to the Html when you first clikc.
Second click checks if the class exists. If exists it removes it.

Categories