I have a multiple select html element.
I want to catch the resize event, so I can store the latest value.
<select multiple="multiple" class="ra-multiselect-collection" style="resize: vertical; margin-top: 0px; margin-bottom: 5px; height: 527px;"></select>
The following code doesnt work:
$('.ra-multiselect-collection').on( 'resize', function(){
alert('resized');
});
Any ideas?
Well, I don't think that you can bind a resize event to a DOM element, but check this out:
$("select").on("mouseup", function()
{
var el = $(this);
if (el.data("old-height") == null || el.data("old-height") != el.height())
{
alert("resized!");
}
el.data("old-height", el.height());
}).data("old-height", $("select").height());
Fiddle
I have used mouseup event checking the old height stored in a data property with the current height on the moment of the event. If they are different, you get a resize event. Not a pretty beautiful workaround, but it seems to work.
I could not test on IE because it doesn't support that property and on Firefox, it works nice but it seems that you can double-click the resize corner and it returns to the initial size and this doesn't trigger the event actually.
In your case, as you're using a class to select those elements, you can do this:
$(".ra-multiselect-collection").each(function()
{
$(this).on("mouseup", function()
{
var el = $(this);
if (el.data("old-height") == null || el.data("old-height") != el.height())
{
alert("resized!");
}
el.data("old-height", el.height());
}).data("old-height", $(this).height());
});
Didn't tested but it should work.
Finally I used resizable function from jQuery UI
http://jqueryui.com/resizable/
This is my code:
$('.ra-multiselect-collection').first().resizable({
resize: function() {
alert('resized');
}
});
Maybe that .first() isn't necessary
You dont have resize event here, but u can store the size on mousedown event, and check if it changed on mouseup event
Related
I'm currently using jQuery to make a div clickable and in this div I also have anchors. The problem I'm running into is that when I click on an anchor both click events are firing (for the div and the anchor). How do I prevent the div's onclick event from firing when an anchor is clicked?
Here's the broken code:
JavaScript
var url = $("#clickable a").attr("href");
$("#clickable").click(function() {
window.location = url;
return true;
})
HTML
<div id="clickable">
<!-- Other content. -->
I don't want #clickable to handle this click event.
</div>
Events bubble to the highest point in the DOM at which a click event has been attached. So in your example, even if you didn't have any other explicitly clickable elements in the div, every child element of the div would bubble their click event up the DOM to until the DIV's click event handler catches it.
There are two solutions to this is to check to see who actually originated the event. jQuery passes an eventargs object along with the event:
$("#clickable").click(function(e) {
var senderElement = e.target;
// Check if sender is the <div> element e.g.
// if($(e.target).is("div")) {
window.location = url;
return true;
});
You can also attach a click event handler to your links which tell them to stop event bubbling after their own handler executes:
$("#clickable a").click(function(e) {
// Do something
e.stopPropagation();
});
Use stopPropagation method, see an example:
$("#clickable a").click(function(e) {
e.stopPropagation();
});
As said by jQuery Docs:
stopPropagation method prevents the event from bubbling up the DOM
tree, preventing any parent handlers from being notified of the event.
Keep in mind that it does not prevent others listeners to handle this event(ex. more than one click handler for a button), if it is not the desired effect, you must use stopImmediatePropagation instead.
Here my solution for everyone out there looking for a non-jQuery code (pure javascript)
document.getElementById("clickable").addEventListener("click", function(e) {
e = window.event || e;
if(this === e.target) {
// put your code here
}
});
Your code wont be executed if clicked on parent's children
If you do not intend to interact with the inner element/s in any case, then a CSS solution might be useful for you.
Just set the inner element/s to pointer-events: none
in your case:
.clickable > a {
pointer-events: none;
}
or to target all inner elements generally:
.clickable * {
pointer-events: none;
}
This easy hack saved me a lot of time while developing with ReactJS
Browser support could be found here: http://caniuse.com/#feat=pointer-events
Inline Alternative:
<div>
<!-- Other content. -->
<a onclick='event.stopPropagation();' href="http://foo.example">I don't want #clickable to handle this click event.</a>
</div>
You can also try this
$("#clickable").click(function(event) {
var senderElementName = event.target.tagName.toLowerCase();
if(senderElementName === 'div') {
// Do something here
} else {
// Do something with <a> tag
}
});
Writing if anyone needs (worked for me):
event.stopImmediatePropagation()
From this solution.
Using return false; or e.stopPropogation(); will not allow further code to execute. It will stop flow at this point itself.
If you have multiple elements in the clickable div, you should do this:
$('#clickable *').click(function(e){ e.stopPropagation(); });
I compare to ev.currentTarget when this is not available (React, etc).
$("#clickable").click(function(e) {
if (e.target === e.currentTarget) {
window.location = url;
return true;
}
})
Here's an example using Angular 2+
For example, if you wanted to close a Modal Component if the user clicks outside of it:
// Close the modal if the document is clicked.
#HostListener('document:click', ['$event'])
public onDocumentClick(event: MouseEvent): void {
this.closeModal();
}
// Don't close the modal if the modal itself is clicked.
#HostListener('click', ['$event'])
public onClick(event: MouseEvent): void {
event.stopPropagation();
}
If it is in inline context, in HTML try this:
onclick="functionCall();event.stopPropagation();
e.stopPropagation() is a correct solution, but in case you don't want to attach any event handler to your inner anchor, you can simply attach this handler to your outer div:
e => { e.target === e.currentTarget && window.location = URL; }
var inner = document.querySelector("#inner");
var outer = document.querySelector("#outer");
inner.addEventListener('click',innerFunction);
outer.addEventListener('click',outerFunction);
function innerFunction(event){
event.stopPropagation();
console.log("Inner Functiuon");
}
function outerFunction(event){
console.log("Outer Functiuon");
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Pramod Kharade-Event with Outer and Inner Progration</title>
</head>
<body>
<div id="outer" style="width:100px;height:100px;background-color:green;">
<div id="inner" style="width:35px;height:35px;background-color:yellow;"></div>
</div>
</body>
</html>
You need to stop the event from reaching (bubbling to) the parent (the div).
See the part about bubbling here, and jQuery-specific API info here.
To specify some sub element as unclickable write the css hierarchy as in the example below.
In this example I stop propagation to any elements (*) inside td inside tr inside a table with the class ".subtable"
$(document).ready(function()
{
$(".subtable tr td *").click(function (event)
{
event.stopPropagation();
});
});
You can check whether the target is not your div-element and then issue another click event on the parent after which you will "return" from the handle.
$('clickable').click(function (event) {
let div = $(event.target);
if (! div.is('div')) {
div.parent().click();
return;
}
// Then Implement your logic here
}
Here is a non jQuery solution that worked for me.
<div style="background:cyan; width:100px; height:100px;" onclick="if (event.srcElement==this) {console.log('outer');}">
<a style="background:red" onclick="console.log('inner');">Click me</a>
</div>
for those that are not using jQuery
document.querySelector('.clickable').addEventListener('click', (e) =>{
if(!e.target.classList.contains('clickable')) return
// place code here
})
In case someone had this issue using React, this is how I solved it.
scss:
#loginBackdrop {
position: absolute;
width: 100% !important;
height: 100% !important;
top:0px;
left:0px;
z-index: 9; }
#loginFrame {
width: $iFrameWidth;
height: $iFrameHeight;
background-color: $mainColor;
position: fixed;
z-index: 10;
top: 50%;
left: 50%;
margin-top: calc(-1 * #{$iFrameHeight} / 2);
margin-left: calc(-1 * #{$iFrameWidth} / 2);
border: solid 1px grey;
border-radius: 20px;
box-shadow: 0px 0px 90px #545454; }
Component's render():
render() {
...
return (
<div id='loginBackdrop' onClick={this.props.closeLogin}>
<div id='loginFrame' onClick={(e)=>{e.preventDefault();e.stopPropagation()}}>
... [modal content] ...
</div>
</div>
)
}
By a adding an onClick function for the child modal (content div) mouse click events are prevented to reach the 'closeLogin' function of the parent element.
This did the trick for me and I was able to create a modal effect with 2 simple divs.
If a child element is clicked, then the event bubbles up to the parent and event.target !== event.currentTarget.
So in your function, you can check this and return early, i.e.:
var url = $("#clickable a").attr("href");
$("#clickable").click(function(event) {
if ( event.target !== event.currentTarget ){
// user clicked on a child and we ignore that
return;
}
window.location = url;
return true;
})
This is what you are looking for
mousedown event. this works on every DOM elements to prevent javascript focus handler like this:
$('.no-focus').mousedown(function (e) {
e.prevenDefault()
// do stuff
}
in vue.js framework, you can use modifier like this:
<span #mousedown.prevent> no focus </span>
Note that using on the input will prevent text selection handler
add a as follows:
....
or return false; from click handler for #clickable like:
$("#clickable").click(function() {
var url = $("#clickable a").attr("href");
window.location = url;
return false;
});
All solution are complicated and of jscript. Here is the simplest version:
var IsChildWindow=false;
function ParentClick()
{
if(IsChildWindow==true)
{
IsChildWindow==false;
return;
}
//do ur work here
}
function ChildClick()
{
IsChildWindow=true;
//Do ur work here
}
<a onclick="return false;" href="http://foo.example">I want to ignore my parent's onclick event.</a>
I'm trying to listen to focus / blur events on span with contenteditable=true attribute.
So here's what I tried (jQuery) :
$('.editable').on('focus',function(){
var that = $(this),
defaultTxt = that.data('default');
that.html('');
});
$('.editable').on('blur',function(){
var that = $(this),
defaultTxt = that.data('default');
if(that.html() === ''){
that.html(defaultTxt);
}
});
But he doesn't seem to work, because span doesn't handle focus / blur. How can I achieve that anyway (IE8 support needed) ?
There are two ways to achieve this effect.
Approach 1: focusin and focusout
$('.editable').on('focusin', function() {
// your code here
});
$('.editable').on('focusout', function() {
// your code here
});
focusin and focusout are like focus and blur events, but unlike the latter, they are fired on almost(?) every element, and also bubble. focusin and focusout are a part of DOM level 3 Specification. Firefox 51 and older didn't support this due to a known bug, but Firefox 52 and above have full support.
Approach 2: click and focus
This only works if you have other focusable elements around your span. What you do is basically use the focus event on any other element as a blur handler.
$('.editable').on('click', function() {
// your code here
});
$('*').on('focus', function() {
// handle blur here
// your code here
});
I wouldn't recommend this approach in a large webapp, because browser performance will take a hit.
I have created a demo for you:
$('.editable').bind('click', function(){
$(this).attr('contentEditable',true);
});
$('.editable').bind('focus', function() {
var that = $(this);
//defaultTxt = that.data('default');
that.html('');
});
$('.editable').bind('blur', function() {
var that = $(this);
var defaultTxt = that.data('default');
if(that.html() === ''){
that.html(defaultTxt);
}
});
.editable{
padding: 5px;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<span class="editable" data-default="default">Some text</span>
I have changed your code, take a look it. Also now it's keeping the old value when lost the focus if you don't type anything.
Is there any way to listen for elements being shown or hidden?
I would like categorically to--whenever an element goes from hidden to shown--put focus on the first input element within the newly shown element
I thought of attaching a click event to everything and putting it at the top of the document, thinking that would trigger before anything and I could track whether the clicked element's next("div") (or something) would have a css display property of none, then setting a small timeout, then setting the focus, but I get undefined when I try to access that CSS property
$("html").on("click", "body", function(){
alert($(this).next("div").css("display")); //undefined
});
Is there a way to do this?
You can try something like this (it’s kind of a hack). If you monkey-patch the css/show/hide/toggle prototypes in jQuery, you can test if the element changes it’s :hidden attribute after a "tick" (I used 4ms). If it does, it has changed it’s visibility. This might not work as expected for animations etc, but should work fine otherwise.
DEMO: http://jsfiddle.net/Bh6dA/
$.each(['show','hide','css','toggle'], function(i, fn) {
var o = $.fn[fn];
$.fn[fn] = function() {
this.each(function() {
var $this = $(this),
isHidden = $this.is(':hidden');
setTimeout(function() {
if( isHidden !== $this.is(':hidden') ) {
$this.trigger('showhide', isHidden);
}
},4);
});
return o.apply(this, arguments);
};
})
Now, just listen for the showhide event:
$('div').on('showhide', function(e, visible) {
if ( visible ) {
$(this).find('input:first').focus();
}
});
Tada!
PS: I love monkeypatching
You could:
var allEls = $('body *');
function isDisplayBlock(arr) {
var isBlock = [];
$.each(arr, function(i, e){
if ($(e).css('display') === 'block') {
isBlock.push(e);
}
})
return isBlock;
}
But ive no idea how to check if they changed, instead of just checking if they are block.
You can just use $('div:visible') to check whether a div has display: block or display: none. Those are the only two values that :visible looks at anyway.
Source: How do I check if an element is hidden in jQuery?
-edit-
I realise I didn't read thoroughly, you're asking about an event that tells you when display changed. There is none, see Nelson's comment on your question.
I have a jsfiddle Here: http://jsfiddle.net/zAFND/616
Now if you open up fiddle in IE (I use IE9) and firefox, if you double click on a check box button, it turns it on but does not turn it off. But if you open it up in opera, safarai and chrome, it works fine if you double click or click in quick succession.
My question is how to allow quick succession clicks to work correctly in firefox and IE9?
Code:
HTML:
<div id="ck-button"><label>
<input type="checkbox" name="options[]" id="optionA" value="A" /><span>A</span></label>
</div>
CSS:
#ck-button {
margin:8px;
background-color:#EFEFEF;
border:1px solid #D0D0D0;
overflow:auto;
float:left;
position: relative;
}
#ck-button label {
float:left;
width:4.0em;
cursor:pointer;
}
#ck-button label span {
text-align:center;
padding:3px 0px;
display:block;
}
#ck-button label input {
position:absolute;
top:-20px;
}
#ck-button input:checked + span {
background-color:green;
color:white;
}
Jquery/javasscript:
$(document).ready(function(){
$("body").css("-webkit-user-select","none");
$("body").css("-moz-user-select","none");
$("body").css("-ms-user-select","none");
$("body").css("-o-user-select","none");
$("body").css("user-select","none");
});
This is a bug in Firefox. See Bug 608180 - Double/rapid clicking a checkbox label does not work as expected
IE has, for historical reasons (but fixed in more recent versions), a bugged event model that skips the second mousedown and click events on a double click. See bug 263 - beware of DoubleClick in IE.
I've made a plugin that fixes some bugs in jQuery UI button widget as well as working around the Firefox bug not long ago, shouldn't be hard to adapt it to your non-jQuery UI buttons.
Extracted the important part and adapted it for nested checkboxes inside labels:
(function () {
var mdtarg, //last label mousedown target
mdchecked, //checked property when mousedown fired
fixedLabelSelector = '.fixedLabelCheckbox'; //edit as you see fit
$(document).on('mousedown', fixedLabelSelector, function (e) {
//only left clicks will toggle the label
if (e.which !== 1) return;
mdtarg = this;
mdchecked = this.control ? this.control.checked : $(this).find('input')[0].checked;
//reset mdtarg after mouseup finishes bubbling; prevents bugs with
//incorrect mousedown-mouseup sequences e.g.
//down IN label, up OUT, down OUT, up IN
$(document).one('mouseup', function () {
mdtarg = null;
});
}).on('mouseup', fixedLabelSelector, function (e) {
if (e.which !== 1) return;
if (mdtarg === this) {
var ch = this.control || $(this).find('input')[0];
//the click event is supposed to fire after the mouseup so
//we wait until mouseup and click finish bubbling and check if it
//had the desired effect
setTimeout(function () {
if (mdchecked === ch.checked) {
//else patch it manually
ch.checked = !ch.checked;
$(ch).change();
}
}, 0);
}
});
}());
Fiddle tested in Firefox.
You have to add the fixedLabelCheckbox class to all labels containing checkboxes that you'd like to fix with the code above.
It will work regardless of where you put the script and it also fixes dynamically added checkboxes as long as the label has the corresponding delegated class/selector.
Note that if you're using other libraries, this may not fire the change handlers bound outside of jQuery.
If you don't feel like adding extra classes to your markup, you can use this version (more code and less performance):
(function ($) {
function getControl(lbl) { //fallback for non-HTML5 browsers if necessary
return lbl.control || (lbl.htmlFor ? $('input[id="'+lbl.htmlFor+'"]')[0] : $(lbl).find('input')[0]);
}
var mdtarg, //last label mousedown target
mdchecked; //checked property when mousedown fired
$(document).on('mousedown', 'label', function (e) {
//only left clicks will toggle the label
if (e.which !== 1) return;
var ch = getControl(this);
if (!ch || ch.type !== 'checkbox') return;
mdtarg = this;
mdchecked = ch.checked;
//reset mdtarg after mouseup finishes bubbling; prevents bugs with
//incorrect mousedown-mouseup sequences e.g.
//down IN label, up OUT, down OUT, up IN
$(document).one('mouseup', function () {
mdtarg = null;
});
}).on('mouseup', 'label', function (e) {
if (e.which !== 1) return;
if (mdtarg === this) {
var ch = getControl(this);
//the click event is supposed to fire after the mouseup so
//we wait until mouseup and click finish bubbling and check if it
//had the desired effect
setTimeout(function () {
if (mdchecked === ch.checked) {
//else patch it manually
ch.checked = !ch.checked;
$(ch).change();
}
}, 0);
}
});
}(jQuery));
Fiddle
As you can see from the code above, this version should work with both label's for attribute as well as nested inputs inside the label, without adding any extra markup.
About disabling selection: you can either put the user-select in the CSS as commented in your question, or, if browsers that don't support the user-select are also concerned, apply this answer on all labels that you want to have selection disabled.
You could add browser detection and then, if IE or Firefox, add the ondblclick event via JS to invert the checkbox.
You can't just set it unconditionally, since some browsers (Safari, Chrome) transmit two clicks and a dblclick, while others (IE, Firefox) transmit only one click and one dblclick. On the former, the two click events will invert the field twice. On the latter, only one click event fires and thus the field is only inverted once; to mitigate this, you need to make dblclick invert the field so that two clicks invert it an even number of times.
Hope this helps!!
I need to get the newly focussed element (if any) while executing an onBlur handler.
How can I do this?
I can think of some awful solutions, but nothing which doesn't involve setTimeout.
Reference it with:
document.activeElement
Unfortunately the new element isn't focused as the blur event happens, so this will report body. So you are gonna have to hack it with flags and focus event, or use setTimeout.
$("input").blur(function() {
setTimeout(function() {
console.log(document.activeElement);
}, 1);
});
Works fine.
Without setTimeout, you can use this:
http://jsfiddle.net/RKtdm/
(function() {
var blurred = false,
testIs = $([document.body, document, document.documentElement]);
//Don't customize this, especially "focusIN" should NOT be changed to "focus"
$(document).on("focusin", function() {
if (blurred) {
var elem = document.activeElement;
blurred = false;
if (!$(elem).is(testIs)) {
doSomethingWith(elem); //If we reached here, then we have what you need.
}
}
});
//This is customizable to an extent, set your selectors up here and set blurred = true in the function
$("input").blur(function() {
blurred = true;
});
})();
//Your custom handler
function doSomethingWith(elem) {
console.log(elem);
}
Why not using focusout event? https://developer.mozilla.org/en-US/docs/Web/Events/focusout
relatedTarget property will give you the element that is receiving the focus.