Avoid double clicking when using jQuery to mark checkbox - javascript

I am trying to allow clicking on a div that contains a checkbox to cause that checkbox to be selected. Whenever the checkbox is selected, its parent div changes color. When unselected, the parent div's background color goes back to the original one.
Problem: The behavior when clicking on the checkbox's div is correct. However, when clicking on the checkbox directly, the behavior is opposite of what is desired. I suspect this is due to double clicking: The checkbox's own click handler fires, as well as the click handler for its parent div. I may be wrong here. How can I fix it?
JS
// Click checkbox when its container is clicked
$(".organizer_listing_checkbox_container_container").click(function(event) {
if (event.target.type !== 'checkbox') {
$(':checkbox', this).trigger('click');
}
});
// Highlight row on selecting Checkbox
$(".organizer_listing_checkbox").click(function() {
if($(this).attr('checked')) {
$(this).parent().parent().parent().css('background-color', "#FAFAFA");
} else {
$(this).parent().parent().parent().css('background-color', "#FFF");
}
});
HTML
<div class="organizer_listing">
<div class="organizer_listing_checkbox_container_container">
<div class="organizer_listing_checkbox_container" data-listing_id=1234>
<input type="checkbox" class="organizer_listing_checkbox" />
</div>
</div>
</div>
EDIT: Swapped the background colors + e.stopPropagation()
// Click checkbox when its container is clicked
$(".organizer_listing_checkbox_container_container").click(function(event) {
$(':checkbox', this).trigger('click');
});
// Highlight row on selecting Checkbox
$(".organizer_listing_checkbox").click(function(e) {
e.stopPropagation();
if($(this).attr('checked')) {
$(this).parent().parent().parent().css('background-color', "#FAFAFA");
} else {
$(this).parent().parent().parent().css('background-color', "#FFF");
}
});

You might want to try using a label and then use a change handler on the check box. Clicking on a label associated with a checkbox is functionally the same as clicking on the checkbox. By using a change handler, you process all the events where the value of the checkbox changes.
<style>
.organizer_listing_checkbox_container {
display: block;
}
</style>
<script type="text/javascript">
$(function() {
$(".organizer_listing_checkbox").on('change',function() {
if ($(this).attr('checked')) {
$(this).parent().parent().parent().css('background-color', "#FAFAFA");
} else {
$(this).parent().parent().parent().css('background-color', "#FFF");
}
});
});
</style>
<div class="organizer_listing">
<div class="organizer_listing_checkbox_container_container">
<label class="organizer_listing_checkbox_container" for="listing_checkbox_0" data-listing_id=1234>
<input id="listing_checkbox_0" type="checkbox" class="organizer_listing_checkbox" />
</label>
</div>
</div>

I kind of went crazy and rewrote most of the code (demo):
var update = function($el){
// cycle through all elements
$el.each(function(){
var bkgd = $(this).prop('checked') ? "#FAFAFA" : "#FFF";
$(this).closest('.organizer_listing_checkbox_container_container')
.css('background-color', bkgd);
});
};
// Click checkbox when its container is clicked
$(".organizer_listing_checkbox_container_container").click(function(event) {
var check = $(':checkbox', this);
check.prop('checked', !check.prop('checked') );
update( check );
});
// Highlight row on selecting Checkbox
$(".organizer_listing_checkbox").click(function(e) {
e.stopPropagation();
update( $(this) );
});
// update on initialization
update( $(".organizer_listing_checkbox") );

Use the on() to bind events (jQuery 1.7+). The following method will:
Toggle colours on change of the checkbox (Use change instead of click to allow keyboard-initiated state changes).
Toggle the check state on clicking the <div>
Demo: http://jsfiddle.net/sPb9f/1/
// Click checkbox when its container is clicked
$('.organizer_listing').on('click', '.organizer_listing_checkbox_container_container', function(event) {
if ($(event.target).hasClass('organizer_listing_checkbox')) {
return; // Do nothing (checkbox)
}
$(':checkbox', this).each(function(){
this.checked = !this.checked; // Swap check state
}).trigger('change');
}).on('change', '.organizer_listing_checkbox', function(event) {
// Highlight row on selecting Checkbox
var $this = $(this),
$main_listing = $this.closest('.organizer_listing');
if (this.checked) {
$main_listing.css('background-color', "red");
} else {
$main_listing.css('background-color', "yellow");
}
});

You have just to stop propagation:
// Highlight row on selecting Checkbox
$(".organizer_listing_checkbox").click(function(e) {
e.stopPropagation();//so the click will not propagate to the div parent
if($(this).attr('checked')) {
$(this).parent().parent().parent().css('background-color', "#FFF");
} else {
$(this).parent().parent().parent().css('background-color', "#FAFAFA");
}
});

Related

Issue with quiz and jQuery

I have written simple quiz with two cards. After user have clicked on the card, attribute clicked change status and answer is checked.
clicked = false;
$(document).on("click", "#card1", function() {
clicked = true;
check answer........
});
I have got antoher on click event, which should load next question when user click on body element.
This event should only work when the card is clicked and clicked status is true.
$(document).on("click", "body", function() {
if (clicked == true) {
quiz.nextQuestion();
clicked = false;
}
});
But these two onclick events start and execute simultaneously.
How can I prevent this?
stopPropagation(); can be used for this. Otherwise click on elements inside will also trigger the body click functions.
One more thing is that, we have to give click for <html> rather than <body>.
Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
clicked = false;
$(document).on("click", "#card1", function(e) {
e.stopPropagation();
clicked = true;
console.log('click card');
});
$(document).on("click", "html", function(e) {
if (clicked == true) {
console.log('click body');
clicked = false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="card1">
Card1
</div>
</body>
Simple...
clicked = false;
$(document).on("click", "#card1", function() {
clicked = true;
//check answer........
$(this).on("click", "body", function() {
if (clicked == true) {
quiz.nextQuestion();
clicked = false;
}
});
});
Hope this helps.....
You can do it by changing the status of clicked as true after you have checked the answer.
$(document).on("click", "#card1", function() {
check answer........
clicked = true;
});
This will make sure that clicked is not made true as soon as the click event is fired hence making the if statement in the second part of the code false
OR
You can even do it by
clicked = 0;
$(document).on("click", "#card1", function() {
clicked = 1;
check answer........
});
$(document).on("click", "body", function() {
if (clicked == 2) {
quiz.nextQuestion();
clicked = 0;
}else
{
clicked +=1;
}
});

Menu should disappear when clicked somewhere else

I have a div which should be visible, whenever a button is clicked. It's like a menu. Afterwards, it should disappear (toggle), when the button is clicked again or when the user clicks somewhere else on the page (whole body).
In my current approach, the menu constantly toggles, so both functions (see below) are being triggered.
$("#b1").click(function() {
$("#menu").toggle("slide");
});
$("body").click(function() {
if ($("#menu").is(":visible")) {
$("#menu").toggle("slide");
}
});
How should I improve my code, so that the menu only disappears when the button is clicked again or when the user clicks somewhere else?
Here is a fiddle.
Use $(window) to attach the event, then you can close the menu anywhere.
$("#b1").click(function() {
$("#menu").toggle("slide");
return false;
});
$(window).click(function() {
if ($("#menu").is(":visible")) {
$("#menu").toggle("slide");
}
});
Check demo: https://jsfiddle.net/wru8mvxt/5/
You can use e.target and check whenever it's not the menu or the button which got clicked. Otherwise the menu closed even on the button click or on a click inside.
$("#b1").click(function() {
$("#menu").slideDown();
});
$("body").click(function(e) {
if (!$(e.target).is("#b1") && $("#menu").is(":visible")) {
$("#menu").slideUp();
} else {
e.preventDefault();
}
});
If you want the menu to stay even on click inside, just add && !$(e.target).is("#menu") to the if condition.
Working example.
I think your code looks good.. I see one problem when you click on menu it will be hide.
$("#b1").click(function() {
$("#menu").toggle("slide");
return false; // prevent to pass click event to body
});
$("body").click(function() {
if ($("#menu").is(":visible")) {
$("#menu").toggle("slide");
}
});
$("#menu").click(function(e){
e.preventDefault();
return false;
});
Use something like this:
$(document).mouseup(function (e)
{
var container = $("YOUR CONTAINER SELECTOR");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.hide();
}
});
Try this.
$("#b1").click(function() {
event.stopPropagation();
$("#menu").toggle("slide");
});
$("body").click(function() {
if(!$(event.target).closest('#menu').length){
if ($("#menu").is(":visible")) {
$("#menu").toggle("slide");
}
}
});
I think this code will solve your issue. You can use e.target property to find whether user clicked on button or outside button. When user click on button b1 it enters both b1 click event and body click event. So if in order to find where the user is clicked you can use event.target property.
Clicking the button will toggle the menu visibility.
Clicking outside the button will close the menu if it is opened.
$("#b1").click(function() {
$("#menu").toggle("slide");
$("#b1").text() == "hide menu" ? $("#b1").text("show menu") : $("#b1").text("hide menu");
});
$("body").click(function(e) {
if (!$(e.target).is("#b1") && $("#menu").is(":visible")) {
$("#menu").slideUp();
}
else {
e.preventDefault();
}
});
Working fiddle
You have to do following changes.
$(document).ready(function() {
$("#b1").click(function(e) {
$("#menu").slideToggle();
e.stopPropagation();
});
$(document).click(function(e) {
if (!$(e.target).is('#menu, #menu *')) {
$("#menu").slideUp();
}
});
});

Display menu on focus and hide when out of focus or clicked other than the menu

I am trying to display menu (#lorem-ipsum-wrapper) when the div (#content) is focused, and again hide the menu if neither the div or the menu is clicked.
js:
$(document).ready(function() {
console.log('ready');
$('#content').on("focus", function(event) {
$('#lorem-ipsum-wrapper').css("display", "block");
event.stopPropagation();
});
$(document).on("click", function() {
$('#lorem-ipsum-wrapper').css("display", "none");
});
});
demo at codepent.io
But the problem is that as soon as the #content is in focus, the menu displays and then again hides itself. Isn't the stopPropagation() method used to stop this? What am I doing wrong? Your help will be very much appreciated. Thank you.
Does this help ?
$(document).click(function(e) {
var e = $(e.target), eid = e.attr("id");
if (!e.parents("#lorem-ipsum-wrapper").length && !e.parents("#content-wrapper").length && eid !== "content-wrapper" && eid !== "lorem-ipsum-wrapper") {
$('#lorem-ipsum-wrapper').css("display", "none");
}
});
or you can use blur event :
$('#content').on("focus", function(event) {
$('#lorem-ipsum-wrapper').css("display", "block");
});
$('#content').on("blur", function(event) {
$('#lorem-ipsum-wrapper').css("display", "none");
});
If I didn't misunderstand, you want to hide #lorem-ipsum-wrapper if #content is not clicked and show the #lorem-ipsum-wrapper on click of #content. Then, your code should be:
$(document).ready(function() {
console.log('ready');
$('#lorem-ipsum-wrapper').css('display','none');
$('#content').on("focus", function(event) {
$('#lorem-ipsum-wrapper').css('display','block');
});
$('#content').on("blur", function() {
$('#lorem-ipsum-wrapper').css("display", "none");
});
$('#lorem-ipsum-wrapper').on("click",function(){
$(this).css("display","block");
});
Explanation:
The third lines ensures that the lorem-ipsum-wrapper is not show before executing any code.
The fourth and fifth lines make the #lorem-ipsum-wrapper visible whenever the focus is on the #content.
The seventh and eighth lines make the lorem-ipsum-wrapper hidden whenever the users clicks somewhere else on the page or make the #lorem-ipsum-wrapper lose focus.

Why isn't my checkbox change event triggered?

I have two functions.
The first function translates a div click into a checked/unchecked toggle.
The second function translates a checkbox change into a hide/show event.
The problem is that when I use the first function to check/uncheck the box, the second function is not called. I am new to javascript, thanks.
<script type="text/javascript">
$(document).ready(function() {
$(":checkbox").parent().click(function(evt) {
if (evt.target.type !== 'checkbox') {
var $checkbox = $(":checkbox", this);
$checkbox.attr('checked', !$checkbox.attr('checked'));
evt.stopPropagation();
return false;
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$(":checkbox").change(function() {
if($(this).attr("checked")) {
$('.'+this.id).show();
}
else {
$('.'+this.id).hide();
}
});
});
</script>
The change event does not fire when you programmatically change the value of a check box. What you can do to ensure it fires is:
$(":checkbox").parent().click(function(evt) {
if (evt.target.type !== 'checkbox') {
var $checkbox = $(":checkbox", this);
$checkbox.attr('checked', !$checkbox.attr('checked'));
$checkbox.change();
}
});
Don't bother with the first snippet. Just use LABEL elements:
<label><input type="checkbox">Some option</label>
Now, when the user clicks the label (the text next to the checkbox), the checkbox will be activated.
The second snippet can be optimized:
$('input:checkbox').change(function() {
$('#' + this.id).toggle(this.checked);
});
you are using '.' which is for class selectors instead use '#' since you are using the element ID. Like this:
$(document).ready(function() {
$(":checkbox").bind('change', function() {
if($(this).attr("checked")) {
$('#'+this.id).show();
}
else {
$('#'+this.id).hide();
}
});
});

jQuery is mousedown on mouseover

I have a table where i want to change cell background on mouse over and mouse button down, my current solution doesn't work as I want it to :
function ChangeColor(sender) {
sender.style.backgroundColor = 'yellow';
}
var clicking = false;
$(document).mouseup(function() {
clicking = false;
});
$(document).ready(function() {
$('#Table1 tr').each(function() {
$('td', this).each(function() {
$(this).mousedown(function() {
clicking = true;
});
$(this).mousedown(function(event) {
if (clicking==true) { ChangeColor(this); }
});
});
});
});
Is there any way to make it work like that ?
EDIT: Given your comment above, you could do something like this:
$(document).ready(function() {
isMouseDown = false
$('body').mousedown(function() {
isMouseDown = true;
})
.mouseup(function() {
isMouseDown = false;
});
$('Table1 tr td').mouseenter(function() {
if(isMouseDown)
$(this).css({backgroundColor:'orange'});
});
});
This will color the background of the td when you mouseover, but only if the mouse button is down.
Sounds like you just want to change the color when you click. If that's the case, it is much simpler than what you're attempting.
$(document).ready() {
$('#Table1 tr td').click(function() {
$(this).css({backgroundColor:'yellow'});
});
});
This will change the background of the td elements yellow when you click them.
It will be similar to change the color when you mouseover.
EDIT: Just noticed the title of your question.
If you want to trigger a click when you hover...
$(document).ready() {
$('#Table1 tr td').click(function() {
$(this).css({backgroundColor:'yellow'});
})
.mouseenter(function() {
$(this).click();
});
});
...of course, you could eliminate the click in that case and just change the background with the mouseenter event.

Categories