I'm developing some CSS editor and want to provide ability to change style for <button> when it's clicked. The following code doesn't change background-color to yellow.
http://jsfiddle.net/65erbrhh/
$('a').click(function() {
event.preventDefault();
$('button:active').css('background-color', 'yellow');
});
Edit: In my case, I can't assign specific class to a button, because it's user customizable html.
Since you can't select elements based on their CSS state, one option would be to add a class to the element:
Updated Example
$('a').click(function (e) {
e.preventDefault();
$('button').addClass('active-style');
});
button.active-style:active {
background-color: yellow;
}
But since you said you can't do that, you could alternatively attach an event listener for the mousedown/mouseup events and change the background color accordingly:
Updated Example
$('a').click(function () {
event.preventDefault();
$('button').on('mousedown mouseup', function (e) {
$(this).css('background-color', e.type === 'mousedown' ? 'yellow' : '');
});
});
..but if you want the example to work if you mouseup outside of the button element, you would need to listen to all mouseup events:
Updated Example
$('a').click(function (e) {
e.preventDefault();
$('button').addClass('active-style');
});
$(document).on('mousedown mouseup', function (e) {
var color = (e.type === 'mousedown' && $(e.target).hasClass('active-style')) ? 'yellow' : '';
$('button.active-style').css('background-color', color);
});
Related
I am trying to make a system that would require an admin to click a delete button twice before it fires the action. if he focusout of the button, it resets.
$(".unarmed").css("filter", "grayscale(1)").removeClass("armed").click(function(e) {
$(this).css("filter", "").removeClass("unarmed").addClass("armed");
}).mouseout(function() {
$(this).css("filter", "grayscale(1)").removeClass("armed").addClass("unarmed");
});
$("body").on("click", ".armed", function() {
alert("boom");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="unwait unarmed" src="plus.png">
I've seen jQuery event listener fires before selector applied? but adding e.stopPropagation() causes the second click to not fire.
when e.stopPropagation() is not in the code, it does fire the second click, but together with the first click (i think this means the problem is not with the second click selector)
here is a fiddle with e.stopPropagation():
https://jsfiddle.net/3jyr72t6/
also, if you have suggestion for making it prettier, i'm open for suggestions :D
#icecub answer as snippet:
$(document).ready(function() {
$(".unarmed").css("filter", "grayscale(1)");
$(".unarmed").click(function(e) {
if ($(this).hasClass("armed")) {
console.log("boom");
}
$(this).css("filter", "").removeClass("unarmed").addClass("armed");
}).mouseout(function() {
$(this).css("filter", "grayscale(1)").removeClass("armed").addClass("unarmed");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="unwait unarmed" src="https://kns.im/include/img/plus.png" style="width:50px">
You can always just use the jquery dblclick event. Jquery dblclick
$(document).on("dblclick",".btn-delete",function(){
console.log("DELETE");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn-delete">DELETE</button>
You can use a simple function to detect click outside the element .. See the next example
$("img.unwait").on("click" , function(e){
let $this = $(this);
if($this.hasClass("unarmed")){
$this.removeClass("unarmed").addClass("armed");
}else if($this.hasClass("armed")){
alert("BOOM");
$this.removeClass("armed").addClass("unarmed");
}
});
detect_click_out(".armed" , function(){
$(".armed").removeClass("armed").addClass("unarmed");
});
function detect_click_out(element_selector , action){
$(document).on('click',function(e){
if (!$(element_selector).is(e.target) // if the target of the click isn't the container...
&& $(element_selector).has(e.target).length === 0) // ... nor a descendant of the container
{action();} // run the action as a function
});
}
img{
width : 50px;
}
.unarmed{
filter : grayscale(1);
}
.armed{
filter : grayscale(0);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="unwait unarmed" src="https://png.pngtree.com/element_our/sm/20180515/sm_5afb099d307d3.jpg">
In a script I'm writing with JQuery I'm trying to add a click handler to a div, but ignoring clicks on the children a tags inside it.
You can see a JSFiddle of how I'm currently trying (and failing) to make it happen here: http://jsfiddle.net/q15s25Lx/1/
$(document).ready(function() {
$(document).on('click', '.post:not(a)', function(e) {
alert($(this).text());
});
});
<div class="post">This is some text in a div. Click me please.</div>
In my real page, the a tags all have their own click handlers, so I need to be able to listen for those concurrently.
So, ideally I'd like to use something like the :not() selector to ignore clicks on this particular handler.
Is something like this possible?
You'll need to add another handler that acts on the anchor and stops the event from propagating:
$(document).on('click', '.post a', function (e) {
e.stopPropagation();
e.preventDefault();
});
Without this, when you click the a the event bubbles up to the parent .post, and the handler fires on that anyway.
You need to stop event propagation to child elements using .stopPropagation():
$(document).on('click', '.post a', function(e) {
e.stopPropagation();
});
Working Demo
Just return false; in the end of event handler.
$(document).on('click', '.post', function (e) {
alert($(this).text());//will show entire text
});
$(document).on('click', '.post a', function (e) {
alert($(this).text());//will show 'text'
return false;
});
working fiddle: http://jsfiddle.net/q15s25Lx/2/
return false will server as both e.preventDefault() &
e.stopPropagation()
Try to stop the event from bubbling up the DOM tree using stopPropogation()
$(document).ready(function() {
$(document).on('click', '.post a', function(e) {
e.stopPropagation();
alert($(this).text());
});
});
Fiddle Demo
All of the other posts did not explain why your code failed. Your selector is saying : Find an element that has the class post and is not an anchor. It is NOT saying if a child was clicked and was an achor do not process.
Now there are two ways to solve it. One is to prevent the click from bubbling up from the anchors. You would add another listener on the anchors.
$(document).on('click', '.post a', function (evt) {
evt.stopPropagation(); //event will not travel up to the parent
});
$(document).on('click', '.post', function (evt) {
console.log("Click click");
});
Or the other option is not to add a second event, but check what was clicked.
$(document).on('click', '.post', function (evt) {
var target = $(evt.target); //get what was clicked on
if (target.is("a")) { //check to see if it is an anchor
return; // I am an anchor so I am exiting early
}
console.log("Click click");
});
Or jsut let jquery handle it all for you. return false
$(document).on('click', '.post:not(a)', function() {
alert($(this).text());
return false;
});
I'm trying to add a class on right-click of an element and then remove it when anything else on the page is clicked.
I'm using jQuery.
My function is this so far:
$(".classElement").live('mousedown', function(e) {
if( (e.which == 3) ) {
$(".classElement").addClass("active");
}
e.preventDefault();
}).live('contextmenu', function(e){
e.preventDefault();
});
However, this adds the "active" class to all ".classElement" in the doc, rather than the individual one being clicked. I want to only add the class to the element being clicked.
Also, how can I remove the class when anything else is clicked?
You can removClass active on click of body element, but for this you have to stop event propagation when you are clicking on current element.
$(document).on('mousedown','.classElement', function(e) {
e.preventDefault();
if( (e.which == 3) ) {
$(this).addClass("active");
}
e.stopPropagation();
}).on('contextmenu','.classElement', function(e){
e.preventDefault();
});
$(document.body).click(function(){
$(".classElement").removeClass("active");
});
You can use $(this) to target current clicked element, so you can do:
$(this).addClass("active");
instead of:
$(".classElement").addClass("active");
Also, since .live() was removed since version 1.9, you should use .on() instead.
to target specific element:
$(this).addClass("active");
and to remove it when anything else is clicked, add this:
$(window).one("click", function(){
$(this).removeClass("active");
});
This adds a one time only click event listener to the window.
Use this code
$(".classElement").live('contextmenu', function(e){
e.preventDefault();
if( (e.which == 3) ) {
$(this).addClass("active");
}
});
and then remove class on document click
$(document).click(function(){
$(".classElement").removeClass("active");
});
I want to add custom context menu with jQuery for the whole body of the page, except the textfields. How can I do that?
I have tried that code:
$('body:not(input)').bind('contextmenu', function(){
/*code*/
});
Check the srcElement before plugin executions. If it's not an input element, do trigger the contextmenu plugin:
$(document).on("contextmenu", function(e) {
if (!$(e.srcElement).is(":input")) { // if it's not an input element...
$(this).triggerTheContextMenuPlugin();
}
});
Use an event listener on the document and check if it was initiated by an input element.
$(document).on("contextmenu", function (e) {
if (e.target.tagName.toUpperCase() === "INPUT") {
console.log("context menu triggered");
}
});
Demo here
Inspired by Salman's solution.
You can stop the event propagation in all input elements, with the e.stopPropagation() function. In doing so, you keep the default behavior of the inputs elements:
$(function() {
$(document).on("contextmenu", function(e) {
alert("Context menu triggered, preventing default");
e.preventDefault();
});
$("input").on("contextmenu", function(e) {
e.stopPropagation();
});
});
JSFiddle Demo
I want to control events when hovering a <div> element.
I have my code pretty much working, but I have 2 remaining problems!
When I first run the code in my JSFiddle, I need to click on the body of the document first to get the keydown to be recognised. If I run the code and hover right away and press shift nothing happens. I have it running on doc ready,so not sure why I need to click first? Anyway to get this to work right way without needing to click?
I trace out in the console the console.log('click and press'); This is getting fired each time I press shift and is not looking for a click - why is this getting fired when pressing shift when I call it within a function that says $(document).on('keydown click', function (e) {
DEMO
My JS code is as follows
$(document).ready(function () {
$(".target").hover(function () {
$(document).on('keydown click', function (e) {
if (e.shiftKey) {
// code to go here for click
console.log('click and press');
}
});
$(document).on('keydown', function (e) {
if (e.shiftKey) {
// change cursor to ne-resize
$('.target').css('cursor', 'ne-resize', 'important');
}
});
$(document).on('keyup', function (e) {
// change cursor to sw-resize
$('.target').css('cursor', 'sw-resize', 'important');
});
});
});
Thanks
Your event binding is incorrect. you can use:
Demo: http://jsfiddle.net/g9ea8/8/
Code:
$(document).ready(function () {
var hovering = false;
$(".target").hover(function () {
hovering = true;
}, function() {
hovering = false;
});
$(document).on('click', function (e) {
if (hovering && e.shiftKey) {
// code to go here for click
console.log('hovering+shift+click');
}
});
$(document).on('keydown', function (e) {
if (hovering && e.shiftKey) {
// change cursor to ne-resize
$('.target').css('cursor', 'ne-resize', 'important');
console.log('hovering+shift');
}
});
$(document).on('keyup', function (e) {
// change cursor to sw-resize
if(hovering) {
$('.target').css('cursor', 'sw-resize', 'important');
console.log('hovering+keyup');
}
});
});
The reason why you need to click first on the fiddle demo is because the frame doesn't have focus, normally this should work fine.
You shouldn't be attaching a keydown listener, you only need a to attach click, otherwise keydown will fire the event regardless of a click occurring.
Also, currently you're attaching 3 handlers every time you hover over .target, see #techfoobar's answer for a cleaner solution.