pass eventdata to event handler in javascript - javascript

I have two div :
<div id="div1"></div>
<div id="div2"></div>
and i have the following jquery for div1:
$('#div1').click(function(e)
{
alert(e.pageX + ' ' + e.pageY);
});
.
Now, i want to trigger click eventhandler of div1 to execute on clcicking of div2.
For this i wrote:
$('div2').click(function(e)
{
$('#div1').trigger('click');
});
It's working fine but the problem is i am not able to get e.pageX and e.pageY in the event handler of div1.
How to pass eventdata of div2 click event handler i.e e to div1 click event handler.
Please help.

Since the event you want to trigger is of the same type, you can pass the old event object right along:
$('#div2').click(function (e) {
$('#div1').trigger(e);
});
For events of a different type, you may create a custom event object:
$('#div2').mouseenter(function (e) {
var newE = jQuery.Event('click');
newE.pageX = e.pageX;
newE.pageY = e.pageY;
$('#div1').trigger(newE);
});

jQuerys .trigger()help should be the answer here. You can pass in event-strings (along with parameters) aswell as event objects.
$('#div2').click(function(e) {
$('#div1').trigger(e);
});

Related

onclick event: select item to be clicked by id

I have a button with name="testo_da_inviare" and I can trigger it's click event with:
document.forms['form_da_ricordare'].elements['testo_da_inviare'].onclick
Now I want to replace the button element with an a element that doesn't support the name attribute. So I gave the a element the id="testo_da_inviare"
How do I have to edit my js to trigger the onclick? Javascript is not my cup of tea and I am still learning how to use plain javascript.
You can use getElementById to select it:
document.getElementById('testo_da_inviare').onclick
If you want to fire an event of an element, the right way is to use dispatch method or createEventObject, not to call the element handler name
var eventName = "click";
var element = document.getElementById("testo_da_inviare");
if (document.createEventObject) {
// Dispatch for IE
var evt = document.createEventObject();
element.fireEvent("on" + eventName, evt);
}
else {
// Dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
// Event type, bubbling, cancelable
evt.initEvent(eventName, true, true);
element.dispatchEvent(evt);
}
1- You can let the onclick event trigger on the link/button itself like this:
description
<button onclick="thefunct()">description</button>
function thefunct() {
alert("button clicked");
}
2- Or on the script like this:
document.getElementById("id").onclick = function thefunct(){ alert('button clicked'); };
3- Or using an eventlistener like this:
document.getElementById("id").addEventListener("click", thefunct);
function thefunct() {
alert('button clicked');
}
4- Or using jQuery like this:
$("#id").click(function(){
alert('button clicked');
});
<script src="http://code.jquery.com/jquery-2.2.1.min.js"></script>

Is there a way to trigger mouseup when leaving the document body?

I found some code and I made a jsfillde with it. I need to know how to trigger mouseup in the function below, when you leave document body (in the fiddle example it's like dragging the object into HTML section for instance and leave the mouse click there).
function handleMouseMove(e) {
if (canMove) {
var left = getMousePosX(e);
var top = getMousePosY(e);
var newLeft = ($(elemToMove).css('left').toDecNum() + (left - lastPosX));
var newTop = ($(elemToMove).css('top').toDecNum() + (top - lastPosY));
$(elemToMove).css('left', newLeft);
$(elemToMove).css('top', newTop);
lastPosX = left;
lastPosY = top;
}
return false;
}
Thanks for any suggestion.
You can use
document.onmouseout = handleMouseUp;
This says that when the mouse leaves the document object, the handleMouseUp handler should be called.
Updated fiddle:
http://jsfiddle.net/vp14utt1/1/
-
P.S. for event handlers that simply take the event as an argument, you can just use the function name without wrapping it.
document.onmousedown = function (e) { handleMouseDown(e); };
document.onmousedown = handleMouseDown;
$(elemToMove).trigger('mouseup');
Should do it.
Add this line (new Fiddle):
document.onmouseleave = function (e) { handleMouseUp(e); };
This fires your 'mouse up' logic when the mouse is dragged off the browser window.
To quote The difference between mouseout() and mouseleave():
The mouseout event triggers when the mouse pointer leaves any child elements as well the selected element.
The mouseleave event is only triggered when the mouse pointer leaves the selected element.
I think you want the later.

How to trigger jquery event handler only if events happened in a specific order?

I have the following case. I'm using Bootstrap tabs with MarionetteJS. Whenever a tab click event is fired, I would like to call my handler only after show.bs.tab event is fired for this tab. I do not want to fire my handler if only shown.bs.tab event is fired, since ocassionally I show specific tabs programmatically by calling tab('show') method.
So basically only call handler after the following sequence of events click -> shown.bs.tab
The way I got it to work is the following:
var clicked = false;
this.$el.on('click', 'a[data-toggle="tab"]', function(e) {
clicked = true;
});
this.$el.on('shown.bs.tab', 'a[data-toggle="tab"]', function(e) {
if (clicked === true) {
var moduleId = $(this).attr("data-module");
App.vent.trigger("resultTabClicked", {
module: moduleId
});
}
clicked = false;
});
This is a far cry from an elegant solution is there a better way to achieve this? Perhaps with promises?
If you want to avoid global variables you could attach data to the element itself.
this.$el.on('click', 'a[data-toggle="tab"]', function(e) {
$(this).data('clicked', true);
});
And then
if ($(this).data('clicked') === true) {
...
}
.data() is a jQuery method by the way but you can attach the status anyway you see fit
You can attach the handler to both events and then use event.type and event.timeStamp to keep track of the order in which the events have happened. In the common handler, the event with the highest timestamp happened last; this should help determine when you've struck the right order so as to fire the desired code. See the concept verification demo below:
$(function() {
var times = {click:0,mouseenter:0,mouseleave:0};
$('div.mydiv').on('mouseenter mouseleave click', function(e) {
times[e.type] = e.timeStamp;
$('div.out').text( JSON.stringify( times ) );
});
});
div
{
padding: 20px;
margin: 10px;
border:1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mydiv">hover or click HIRE</div>
<div class="out"></div>

Why is click event handler for a submit button in a colorbox defined in a jQuery prototype method not invoked

I have added a function to jQuery prototype as below. What I want to do is when this method is invoked, generate an html form based on the arguments passed to the method and show it in a colorbox.
(function($) {
$.fn.myFunction = function(data){
var form = $('<form name="people"></form>');
var index;
for (index = 0; index < data.length; index++) {
var match = data[index];
$('<input type="radio" name="person">' + match['name'] + ' [' + match['uri'] + ']<br> ')
.attr("value", match['uri'])
.appendTo(form);
}
$('<input type="button" id="a_button" value="Add"/><br>')
.appendTo(form);
var list = $('<div>').append(form).html();
$('#a_button').click(
function(){
console.log('message from event handler');
}
);
$.colorbox({ innerWidth:420, innerHeight:315, html: list });
};
})(jQuery);
As you can see, form has a button called Add using which I hope to make an ajax request. But unfortunately click event handler attached to this button doesn't seem to be invoked.
Does anyone have any idea about what's wrong here? myFunction is actually invoked by a drupal ajax command in case if that's helpful.
You are appending the form to the DOM after attaching the event handler.
$('#a_button') searches the DOM at that specific point in time, but the form is not added to the DOM until after your call to colorbox with list as a parameter.
Try a permanent delegated event handler instead (or simply add the click handler after the colorbox line).
e.g.
$(document).on("click", "#a_button", function(){
console.log('message from event handler');
});
or
$.colorbox({ innerWidth:420, innerHeight:315, html: list });
$('#a_button').click(
function(){
console.log('message from event handler');
}
);

Passing eventobejct in jquery

I want to pass eventObject with trigger function, means when i manually trigger any event say:
$(".test").bind({ click : Testing });
$('.test').trigger("click");
function Testing(e)
{
}
When the function testing is called by mouseclick , the parameter e contains the eventobject, so i want this same thing when we trigger it manually.Can we pass eventobject when we trigger any event manually, Is this possible?
As gdoron points out (+1), jQuery will supply the event object for you. But you can create it explicitly if you like, to fill it in with information that jQuery can't fill in for you. You can create an Event object and pass it into trigger.
Here's an example of both using the default event object and creating your own: Live copy | source
jQuery(function($) {
$(".test").click(function(e) {
display("Received click on target");
display("typeof e = " + typeof e);
if (e) {
display("e.type = " + e.type);
if (e.type === "click") {
display("Coords: (" + e.pageX + "," + e.pageY + ")");
}
}
});
//Create a new jQuery.Event object without the "new" operator.
var e = $.Event("click");
// Fill in more info
e.pageX = 42;
e.pageY = 27;
// Trigger an artificial click event
display("Issuing a click via <code>$('.test').trigger('click')</code>");
$('.test').trigger("click");
// Trigger an artificial click event
display("Issuing a click creating our own event object with more info on it.");
$('.test').trigger(e);
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
You don't need to do anything, the Event object is there already when you trigger an event as well....
The event object is always passed as the first parameter to an event handler
...
...
trigger docs
Live DEMO

Categories

Resources