JQuery click event and toggleClass method - javascript

I created a simple lottery ticket and I made selector with toggle method.
This is my code.
$( "span" ).click(function() {
$( this ).toggleClass( "span-selected" );
});
The toggle functionality works fine but I want to add a limitation so that only 7 numbers can be chosen in one container. Is there a way to achieve this.
Here is my JSBIN > http://jsbin.com/menawu/1/edit?js,output

You need to check if there are already 7 elements checked in that container, like so:
$( "span" ).click(function() {
if (
$(this).hasClass("span-selected") ||
(!$(this).hasClass(".span-selected") && $(this).closest(".num-cont").find(".span-selected").length < 7)
) {
$( this ).toggleClass( "span-selected" );
}
});
So your criteria are:
if it's not selected, check if there are less than 7: if yes, toggle, otherwise don't do anything
if it is selected, unselect it.

You can use this code;
$( "span" ).click(function() {
if($(this).parent().parent().find('.span-selected').length===7){
alert('Limit');
}
else{
$( this ).toggleClass( "span-selected" );
}
});

Yes,
you can cumulate the count of tickets chosen in a variable and allow toggling only when count is less than 7, based on the jQuery hasClass method to check if your span was previously selected:
var countTicket = 0;
$( "span" ).click(function() {
if($(this).hasClass( "span-selected")) {
countTicket--;
$( this ).toggleClass( "span-selected" );
} else if(countTicket<7) {
$( this ).toggleClass( "span-selected" );
countTicket++;
}
});

Here an example, with multiple case for controle your numbers.
You can easily know if it's unselect/select or if more than 7 span are selected by using hasClass/removeClass/addClass
$("span").click(function(){
if($(this).hasClass("selected"))
{
$(this).removeClass("selected");
}
else{
if($("span.selected").length<7)
{
$(this).addClass("selected");
}
else
console.log("7 span selected");
}
});
span{
width:50px;
height:50px;
margin:10px;
background-color:#eee;
display:inline-table;
}
.selected{
background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span>

just insert count and max variables
var max = 7;
var count = 0;
$("span").click(function() {
if (count < max) {
$(this).toggleClass("span-selected");
count++;
}
});

You can get the number of selected item using the parent container and count them:
$( "span" ).click(function() {
if($(this).closest('.num-cont').find('.span-selected').length==7){
alert('Limit');
}
else{
$( this ).toggleClass( "span-selected" );
}
});

Related

Why doesn't the hidden container reappear when I click on it?

I have a hidden container that contains comments, and a <div> with a <p> inside that says "Show all comments" that I click to show the comments. When I click the div it shows the hidden comments container perfectly, but when I click it again it doesn't hide the comments container. I am thinking there is something wrong with my jQuery code maybe?
var commentsHidden = $( ".comments-container" ).is( ":hidden" );
if (commentsHidden) {
$( ".see-all" ).click(function() {
$('.comments-container').show('slow');
$('.see_hide').text('Hide Comments');
});
} else {
$( ".see-all" ).click(function() {
$('.comments-container').hide();
});
};
When you initialize commentsHidden it is never updated so it always has its initial value. You need to check if its hidden on every click. So you don't need an if statement to attach the event. Just attach a single click event and check inside the event if its hidden and continue accordingly.
$(".see-all").click(function() {
var commentsHidden = $(".comments-container").is(":hidden");
if (commentsHidden) {
$('.comments-container').show('slow');
$('.see_hide').text('Hide Comments');
} else {
$('.comments-container').hide();
}
});
When you call on('click', ..) or its shortcut click(..), you install a new handler. What ends up happening is that you have multiple handlers on the same object, and they all get called. Instead, either install the handler only once:
// In global code or code that gets executed upon module load
// Only once!
$(".see-all").click(function() {
if ($( ".comments-container" ).is( ":hidden" )) {
$('.comments-container').show('slow');
$('.see_hide').text('Hide Comments');
} else {
$('.comments-container').hide();
}
});
or unbind the old handler:
$( ".see-all" ).off('click'); // Unbind all click handlers
var commentsHidden = $( ".comments-container" ).is( ":hidden" );
if (commentsHidden) {
$( ".see-all" ).click(function() {
$('.comments-container').show('slow');
$('.see_hide').text('Hide Comments');
});
} else {
$( ".see-all" ).click(function() {
$('.comments-container').hide();
});
};
You need to check the flag state inside the click function(). The way you have it now will only bind the click handler once on page load.
$( ".see-all" ).click(function() {
var commentsHidden = $( ".comments-container" ).is( ":hidden" );
if (commentsHidden) {
$('.comments-container').show('slow');
$('.see_hide').text('Hide Comments');
} else {
$('.comments-container').hide();
}
});
Try changing to
$( ".see-all" ).click(function() {
var commentsHidden = $( ".comments-container" ).is( ":hidden" );
if (commentsHidden) {
$('.comments-container').show('slow');
$('.see_hide').text('Hide Comments');
});
} else {
$( ".see-all" ).click(function() {
$('.comments-container').hide();
});
}
});
The click handler should only be bound once, and you need to check whether comments are hidden each time the p element is clicked.

jquery if has class issue

I am using bootstrap tabs and I wanted to do some functions with javascript if LI is clicked but with conditional, if it's active do nothing, else do this...
I have come up with this code to check if it has a class="active" since bootstrap tabs adds class="active" to LI for the active tab but it doesn't work well, it always returns true, what I am doing wrong here?
code
var i = $( "li" ).hasClass( "active" );
$( "li" ).click(function() {
if (i == true ) {
console.log("the tab is already active");
}
else {
console.log("selected");
}
});
here is jsfiddle demo
Use $(this) for taken current object
$( "li" ).click(function() {
if ($(this).hasClass("active")) {
console.log("the tab is already active");
}
else {
console.log("selected");
}
});
Fiddle
Check hasClass for clicked li:
$( "li" ).click(function() {
if ($(this).hasClass('active') ) {
console.log("the tab is already active");
}
else {
console.log("selected");
}
});
Because $("li") returns all the li tags. And the initial state of the first li tab is active, so the i variable is always true.
Change the codes to what #Bhojendra Sah wrote will work.
You can try this as well for dynamic elements:
$(document).on('click', "li.active", function (e) {
console.log("the tab is already active");
}).on('click', "li:not(.active)", function (e) {
console.log("selected");
});
Example
$( "li" ).click(function() {
if ($(this).hasClass("active") ) {
console.log("the tab is already active");
}
else {
console.log("selected");
}
});

How do I add time delay

I would like to add a custom class on mouseover. So that when the mouse is hovered over .leftbar, a class is added and it should be popped up(I set css for his). How do I add slow or time delay for the popup?
<script>
$(document).ready(function(){
$( ".leftbar" ).mouseenter(function() {
$( "body" ).addClass( "myclass" );
});
});
$(document).ready(function(){
$( ".leftbar" ).mouseleave(function() {
$( "body" ).removeClass( "myclass1" );
});
});
</script>
I tried this- $( "body" ).addClass( "myclass" , '300'); with no luck
Thank you!
You can use setTimeout
$(document).ready(function(){
$( ".leftbar" ).mouseenter(function() {
window.setTimeout(function(){
$( "body" ).addClass( "myclass" );
}, 300);
});
}):
See https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setTimeout
You could take a look at the jQuery UI method addClass which allows you to pass in some animation parameters into it. View the example and documentation here http://api.jqueryui.com/addClass/
For your use, it should be as simple as adding in the delay to addClass()
Add a reference to the jQuery Library, then change your code to;
$("body").addClass("myclass", 300);
Use a setTimeout, being sure to clear it when the cursor leaves.
Minor error, but myclass != myclass1.
$(document).ready(function(){
var barTimeout = 0;
$( ".leftbar" ).on({
mouseenter: function(){
barTimeout = setTimeout(function(){
$( "body" ).addClass( "myclass" );
}, 300);
},
mouseleave: function(){
if( typeof barTimeout !== 'undefined' ) clearTimeout( barTimeout );
$( "body" ).removeClass( "myclass" );
}
});
});
JSFiddle
You can do it like this:
$(document).ready(function () {
$(".leftbar").hover( function () {
$(this).delay(300).queue(function(next){
$(this).addClass("myclass");
next();
});
}, function(){
$(this).delay(300).queue(function(next){
$(this).removeClass("myclass");
next();
});
});
});
Check it out here: JSFiddle

Toggle one div from two clicks if untoggled

I have a comment section that is initially hidden, and would be revealed by a link on the comment count and/or a link to add comments.
I would like for the comment section to open by either link, but not close if its already opened.
$( "#commentsToggle").click(function() {
$( "#comments" ).toggle( "fast" );
return false;
});
$( ".comment-add a").click(function() {
$( "#comments" ).toggle( "fast" );
return false;
});
See the jsfiddle
http://jsfiddle.net/pQ2np/
Thanks
EDIT: The '#commentsToggle' should be able to toggle (hide) the comments if open, the '.comment-add a' should only show, not hide as it opens an ajax comment form.
This is the code solves my need:
$( "#commentsToggle").click(function() {
$( "#comments" ).toggle( "fast" );
return false;
});
$( ".comment-add a").click(function() {
$( "#comments" ).show( "fast" );
return false;
});
http://jsfiddle.net/pQ2np/6/
If you want them to remain open. use show() instead of toggle().
$( "#commentsToggle").click(function() {
$( "#comments" ).show( "fast" );
return false;
});
$( ".comment-add a").click(function() {
$( "#comments" ).show( "fast" );
return false;
});
You can put both selectors into one function and pass true as the first parameter to showOrhide as referenced in the docs.
$( "#commentsToggle, .comment-add a").click(function() {
$( "#comments" ).toggle( true );
return false;
});
http://jsfiddle.net/pQ2np/3/
Try to use the code in the following link (I have updated your own).
I am not sure why to use toggle and not show. But generally you can check the css display attribute because this is what is used by jquery events.
$( "#commentsToggle").click(function() {
if ($( "#comments" ).css("display") != "block")
$( "#comments" ).toggle( "fast" );
return false;
});
$( ".comment-add a").click(function() {
if ($( "#comments" ).css("display") != "block")
$( "#comments" ).toggle( "fast" );
return false;
});
jsfiddle
Is that you are looking for?
You could use .show() instead of .toggle(), or you could add "true" as one of the parameters:
$( "#commentsToggle").click(function() {
$( "#comments" ).toggle( "fast", true );
return false;
});
$( ".comment-add a").click(function() {
$( "#comments" ).toggle( "fast", true );
return false;
});
Using false instead of true will hide the elements, so using a variable in there could come in useful later.
Here's an updated Fiddle plus enhancements. Below is the gist of it:
$( "#commentsToggle, .comment-add a").click(function (e) {
e.preventDefault();
var $comments = $("#comments");
if ($comments.is(":visible")) {
return;
}
$comments.show("fast");
});
UPDATE: I missed the fact that if you "show" the links again but want to prevent them from being toggled, you only need to use the .show() method. No need for toggle if your intention is for the comments section to appear once and remain open.

show/hide jQuery dialog box on mouseover

I'm trying to make a mouseover map area on an image that must display a dialog box when the mouse is over.
The dialog box content is different, depending on which area it is.
My script actually always show all the dialog boxes.
Here is the jsFiddle I created :
http://jsfiddle.net/U6JGn/4/
and the javascript :
$(function() {
$('#box').dialog( { modal:true, resizable:false } ).parent().find('.ui-dialog-titlebar-close').hide();
for (var i = 0; i < 2; i++) {
$( "#elem"+i ).mouseover(function() {
$( ".box"+i ).dialog( "open" );
});
$( "#elem"+i ).mouseout(function() {
$( ".box"+i ).dialog( "close" );
});
}
});
What am I doing wrong ?
Assign the box dialog to a variable and then don't queue more jquery events with it because it will break your code.
Since Ids need always to be unique we need to do some changes in your html and css
ids: #box0, #box1
class: .box
$(function() {
$('.box').each(function(k,v){ // Go through all Divs with .box class
var box = $(this).dialog({ modal:true, resizable:false,autoOpen: false });
$(this).parent().find('.ui-dialog-titlebar-close').hide();
$( "#elem"+k ).mouseover(function() { // k = key from the each loop
box.dialog( "open" );
}).mouseout(function() {
box.dialog( "close" );
});
});
});
working example: jsfiddle
Try this:
for (var i = 0; i < 2; i++) {
(function(i) {
$( "#elem"+i ).mouseover(function() {
$( ".box"+i ).dialog( "open" );
});
$( "#elem"+i ).mouseout(function() {
$( ".box"+i ).dialog( "close" );
});
})(i);
}
UPDATE:
Take a look at the demo
http://jsfiddle.net/U6JGn/129/
Modified JQuery code....
$(document).ready(function() {
for (var i = 0; i<= 1; i++) {
$( "#elem"+i ).on('mouseenter',function() {
var st = $(this).attr('Id').replace('elem','');
$( ".box" + st).css('display','');
});
$( "#elem"+i ).on('mouseout',function() {
var st = $(this).attr('Id').replace('elem','');
$( ".box"+st ).hide();
});
}
});

Categories