I am using jquery to select an element how do I add the onmousedown event to it and obtain data from the onmousedown parameter?
This is the code that I so far have.
$("#" + that.id).addEventListener(onmousedown(event), function(d) { alert("Hello")});
try this,
$("#" + that.id).mousedown(function(e) { alert("Hello")});
Without jQuery:
Using .addEventListener (recommended):
document.getElementById(this.id).addEventListener("mousedown", function (event) {
console.log(event);
});
Or, using .onmousedown:
document.getElementById(this.id).onmousedown(function (event) {
console.log(event);
});
With jQuery:
Using .on (recommended):
$("#" + this.id).on("mousedown", function (event) {
console.log(event);
});
Or, using .onmousedown:
$("#" + this.id).onmousedown(function (event) {
console.log(event);
});
Related
I'm looking for a way to pass a variable that is relative to the element to both mouseenter and mouseleave events. For example, if I had:
jQuery('.element').on({
mouseenter: function () {
var $child = jQuery(this).find('.child');
$child.fadeIn();
},
mouseleave: function () {
var $child = jQuery(this).find('.child');
$child.fadeOut();
}
});
Is there a way to avoid defining the $child variable twice? I was able to figure this out using .hover(), however I am now unable to use that as I am calling it on dynamically generated elements, for which .hover() will not work.
You can use this way to delegate both events:
jQuery(document).on("mouseenter mouseleave", ".element", function(e){
jQuery(this).find('.child').fadeToggle();
// you can check for e.type for more complex logic
});
The syntax to delegate with different handlers is:
jQuery(document).on({
mouseenter: function () {
//...
},
mouseleave: function () {
//...
}
}, ".element");
Use something like that:
jQuery('.element').on({
mouseenter: function (e) {
var ele = e.currentTarget;
ele.fadeIn();
},
mouseleave: function (e) {
var ele= e.currentTarget;
ele.fadeOut();
}
});
You could reuse the same function in both events, something like:
jQuery('.element').on({
mouseenter: function () {
handleFade("enter", jQuery(this));
},
mouseleave: function () {
handleFade("leave", jQuery(this));
}
});
function handleFade(state, $elem){
var $child = $elem.find('.child');
if(state=="enter"){
$child.fadeIn();
} else if(state=="leave"){
$child.fadeOut();
}
}
I use only HTML5 drag&drop. I did it already by JQuery UI using but now need to do it by clear HTML5 API.
Like I just said: only dragstart fires. The rest of the events I don't catch. In dragstart function all seems to work correct: event.dataTransfer gets data, I checked it.
Here is the code:
$('#widget')
.attr('draggable', 'true')
.on('dragstart', function(event) {
event.preventDefault();
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.setData('text/html', $(this).attr('id'))
event.dataTransfer.setDragImage(event.target, 24, 32);
console.log('Im draggable');
console.log(event.dataTransfer.getData('text/html'));
})
.on('dragend', function(event) {
event.preventDefault();
/*$(this).css('top', event.pageX + "px");
event.dataTransfer.getData('text/html');*/
console.log('dragend');
});
$('#widget_dest')
.click(function(event) {
console.log("click widget_dest");
})
.on('dragenter', function(event) {
event.preventDefault();
console.log("dragenter");
})
.on('dragover', function(event) {
event.preventDefault();
console.log("dragover");
})
.on('drop', function(event) {
event.preventDefault();
event.stopPropagation();
console.log("drop");
var data = event.dataTransfer.getData('text/html');
$(this).append($('#' + data));
$('#' + data).css('top', event.pageX + 'px');
});
});
The only logs I get are: dragstart (correct data) and of the click function.
I purposely inserted click finction to check Widget_dest's properties correctness. Click event fires, the rest of events not.
I'll be very thankful for any help
Victor
You should not be using event.preventDefault() in dragstart. This example works fine: http://jsfiddle.net/noziar/Q3eh3/4/
Also, even if I removed event.preventDefault() in most places, note that in dragover it is necessary, otherwise drop may not fire (at least in Chrome).
As a sidenote, I'm not sure how you're able to read/set properties on event.dataTransfer, since the jQuery event does not have the dataTransfer property - you can use originalEvent for that.
Here is my code:
HTML:
<div id="widget">I'm a widget</div>
<div id="widget_dest">
<span id="widget_box_title">Drag widgets into this box</span>
</div>
CSS:
#widget_dest {
position:absolute;
top: 40px;
border-style:solid;
border-width:1px;
}
#widget {
color:green;
}
#widget_box_title {
color:red;
}
JS:
$('#widget')
.attr('draggable', 'true')
.on('dragstart', function(event) {
var original = event.originalEvent;
original.dataTransfer.effectAllowed = "move";
original.dataTransfer.setData('Text', $(this).attr('id'))
original.dataTransfer.setDragImage(event.target, 24, 32);
console.log('Im draggable');
console.log(original.dataTransfer.getData('Text'));
})
.on('dragend', function(event) {
$(this).css('top', event.pageX + "px");
event.originalEvent.dataTransfer.getData('Text');
console.log('dragend');
});
$('#widget_dest')
.click(function(event) {
console.log("click widget_dest");
})
.on('dragenter', function(event) {
console.log("dragenter");
})
.on('dragover', function(event) {
event.preventDefault();
console.log("dragover");
})
.on('drop', function(event) {
console.log("drop");
var data = event.originalEvent.dataTransfer.getData('Text');
$(this).append($('#' + data));
});
I'm using JQuery tooltip plugin and I'm trying to simulate a input button on hover, which it does successfully but I cannot click on said button. It's like it never exists in the DOM, or maybe it does but then is instantly removed. I'm not sure why the click is not binding.
http://jsfiddle.net/BgDxs/126/
$("[title]").bind("mouseleave", function (event) {
var evt = event ? event : window.event;
var target = $(evt.srcElement || evt.target);
evt.stopImmediatePropagation();
var fixed = setTimeout(
function () {
target.tooltip("close");
}, 200);
$(".ui-tooltip").hover(
function () { clearTimeout(fixed); },
function () { target.tooltip("close"); }
);
});
$("[title]").tooltip({
content: "...wait...",
position: { my: "left top", at: "right center" },
open: function (event, ui) {
var _elem = ui.tooltip;
window.setTimeout(
function() {
var html = "<input type='button' value='Card Information' class='card_info_popup'></input>";
_elem.find(".ui-tooltip-content").html(html);
},
200);
},
track: false,
show: 100
});
$('.card_info_popup').on('click', '.container', function() {
alert('click');
});
You're using event delegation wrongly here since .container is not the child of your input with class card_info_popup, so you need to use:
$('body').on('click', '.card_info_popup', function() {
alert('click');
});
instead of:
$('.card_info_popup').on('click', '.container', function() {
alert('click');
});
Updated Fiddle
change:
$('.card_info_popup').on('click', '.container', function() {
alert('click');
});
to
$(document).on('click', '.card_info_popup', function() {
alert('click');
});
Updated Fiddle
Try this.
You have to use event delegation to enable the click event on the newly created tooltip button
http://learn.jquery.com/events/event-delegation/
$(document).on('click', '.card_info_popup', function() {
alert('click');
});
You have to delegate on('click'); to a static element then bind it to the dynamically generated popup.
I have updated your fiddle: http://jsfiddle.net/BgDxs/130/
Here is the updated code:
$('body').on('click', '.ui-tooltip input.card_info_popup', function() {
alert('click');
});
I have a draggable <div> with a click event and without any event for drag,
but after I drag <div> the click event is apply to <div>.
How can prevent of click event after drag?
$(function(){
$('div').bind('click', function(){
$(this).toggleClass('orange');
});
$('div').draggable();
});
http://jsfiddle.net/prince4prodigy/aG72R/
FIRST attach the draggable event, THEN the click event:
$(function(){
$('div').draggable();
$('div').click(function(){
$(this).toggleClass('orange');
});
});
Try it here:
http://jsfiddle.net/aG72R/55/
With an ES6 class (No jQuery)
To achieve this in javascript without the help of jQuery you can add and remove an event handler.
First create functions that will be added and removed form event listeners
flagged () {
this.isScrolled = true;
}
and this to stop all events on an event
preventClick (event) {
event.preventDefault();
event.stopImmediatePropagation();
}
Then add the flag when the mousedown and mousemove events are triggered one after the other.
element.addEventListener('mousedown', () => {
element.addEventListener('mousemove', flagged);
});
Remember to remove this on a mouse up so we don't get a huge stack of events repeated on this element.
element.addEventListener('mouseup', () => {
element.removeEventListener('mousemove', flagged);
});
Finally inside the mouseup event on our element we can use the flag logic to add and remove the click.
element.addEventListener('mouseup', (e) => {
if (this.isScrolled) {
e.target.addEventListener('click', preventClick);
} else {
e.target.removeEventListener('click', preventClick);
}
this.isScrolled = false;
element.removeEventListener('mousemove', flagged);
});
In the above example above I am targeting the real target that is clicked, so if this were a slider I would be targeting the image and not the main gallery element. to target the main element just change the add/remove event listeners like this.
element.addEventListener('mouseup', (e) => {
if (this.isScrolled) {
element.addEventListener('click', preventClick);
} else {
element.removeEventListener('click', preventClick);
}
this.isScrolled = false;
element.removeEventListener('mousemove', flagged);
});
Conclusion
By setting anonymous functions to const we don't have to bind them. Also this way they kind of have a "handle" allowing s to remove the specific function from the event instead of the entire set of functions on the event.
I made a solution with data and setTimeout. Maybe better than helper classes.
<div id="dragbox"></div>
and
$(function(){
$('#dragbox').bind('click', function(){
if($(this).data('dragging')) return;
$(this).toggleClass('orange');
});
$('#dragbox').draggable({
start: function(event, ui){
$(this).data('dragging', true);
},
stop: function(event, ui){
setTimeout(function(){
$(event.target).data('dragging', false);
}, 1);
}
});
});
Check the fiddle.
This should work:
$(function(){
$('div').draggable({
start: function(event, ui) {
$(this).addClass('noclick');
}
});
$('div').click(function(event) {
if ($(this).hasClass('noclick')) {
$(this).removeClass('noclick');
}
else {
$(this).toggleClass('orange');
}
});
});
DEMO
You can do it without jQuery UI draggable. Just using common 'click' and 'dragstart' events:
$('div').on('dragstart', function (e) {
e.preventDefault();
$(this).data('dragging', true);
}).on('click', function (e) {
if ($(this).data('dragging')) {
e.preventDefault();
$(this).data('dragging', false);
}
});
You can just check for jQuery UI's ui-draggable-dragging class on the draggable. If it's there, don't continue the click event, else, do. jQuery UI handles the setting and removal of this class, so you don't have to. :)
Code:
$(function(){
$('div').bind('click', function(){
if( $(this).hasClass('ui-draggable-dragging') ) { return false; }
$(this).toggleClass('orange');
});
$('div').draggable();
});
With React
This code is for React users, checked the draggedRef when mouse up.
I didn`t use click event. The click event checked by the mouse up event.
const draggedRef = useRef(false);
...
<button
type="button"
onMouseDown={() => (draggedRef.current = false)}
onMouseMove={() => (draggedRef.current = true)}
onMouseUp={() => {
if (draggedRef.current) return;
setLayerOpened(!layerOpened);
}}
>
BTN
</button>
I had the same problem (tho with p5.js) and I solved it by having a global lastDraggedAt variable, which was updated when the drag event ran. In the click event, I just checked if the last drag was less than 0.1 seconds ago.
function mouseDragged() {
// other code
lastDraggedAt = Date.now();
}
function mouseClicked() {
if (Date.now() - lastDraggedAt < 100)
return; // its just firing due to a drag so ignore
// other code
}
Does anyone know how to select any element (possibly on click) on page like body is selected, div is selected, div#foo etc... so i can place it to some variable and edit it later on.
i've tried
$("*", document.body).click(function (e) {
e.stopPropagation();
var domEl = $(this).get(0);
alert("Clicked on - " + domEl.tagName);
});
but it's not working for all elements
You want to get the target property of the event:
$(document).click(function(e) {
e.stopPropagation();
var domEl = e.target; // or $(e.target) to jQuerytize it
alert("Clicked on - " + domEl.tagName);
});
See: http://www.quirksmode.org/js/events_properties.html
Demo: http://jsfiddle.net/karim79/dyHEA/
Try this.
$(function(){
$("*").click(function () {
console.log($(this));
return false;
}
);
});