Get clicked element by a trigger - javascript

Is there any way how to get element selector which was clicked by trigger? I'm trying to avoid specification of certain element in trigger method like $("#certain_element").trigger(e); I want to call a trigger on some position in the page defined by pageX and pageY params and then get an element which was clicked.
var e = new jQuery.Event("click");
e.pageX = 80;
e.pageY = 40;
$('*').trigger(e);
$('*').click(function() {
alert('This element was clicked:'+$(this).get(0).tagName);
});
This script isn't working correctly.

Based on the comments from Andrew and Anurag:
$(document.elementFromPoint(80, 40))
.trigger('click')
.css('background-color', 'blue');

You are triggering it BEFORE binding the click.
var e = new jQuery.Event("click");
e.pageX = 80;
e.pageY = 40;
// binds
$('*').click(function() {
alert('This element was clicked:'+$(this).get(0).tagName);
});
// then triggers
$('*').trigger(e);
Eventhough, if I were you, I'd use another selector, which would not trigger the event for window, document and another unecessary tags.
$(documnet.body).find('*').click(...);
$(document.body).find('*').trigger(e);

Related

Assigning click event to multiple elements with different parameters

I want to give a click event to many elements of the same type, but the function is depending on their position.
I want the click to place a div under the clicked element.
This is what I tried and it's not working.
$("#report-tabs .report-actions").each(function(){
this.click(function(){
var offset = $(this).offset();
this.next().offset({left: offset.left});
});
});
Any suggestions?
Try this
$("#report-tabs .report-actions").on('click', function(){
var offset = $(this).offset();
$(this).next().css('left', offset.left + 'px');
});

in gamequery I am trying to move a selected object with mousetracker by clicking on the object, and dragging it

I know I can use mousedown selection for it, but I am wanting the clicked on sprite to follow my mouse, there is a mousetracker function of sorts mentioned in the api; but unfortunately there are no examples of this other than stating that it allows mouse detection.
//add mousedown events for yarnballs.
$(".gQ_sprite").mousedown(function() {
clickedDivId = $(this).attr('id');
if(clickedDivId.charAt(8) == "-")
{
currentClickedDivId = clickedDivId
$(document).mousemove(function(e){
spriteXPosition = e.pageX
spriteYPosition = e.pageY
});
}
});
I have the location of the mouse selected, just not sure how to get the selected sprite to follow it.
any help would be greatly appreciated.
What Mati said is correct: $.gQ.mouseTracker allows you to access the mouse's state outside of an event handler. The example he gives is correct but it can't be used to move a gQ object (sprite, tile-map or group) around because you'r not allowed to use the .css() function for those. Doing so will break collision detection.
If what you want is to move a gQ object you should do this instead :
$('#' + currentClickedDivId).xy($.gQ.mouseTracker.x, $.gQ.mouseTracker.y);
But since this should be done in a periodical callback, the smoothness of the dragging will depend on the refresh rate.
If you want to use event handlers instead you could modify you code to look like this (without using the mouseTracker):
var clickedDiv;
var clickedDivOffset = {x:0, y:0};
$(".gQ_sprite").mousedown(function(e) {
clickedDiv = $(this);
clickedDivOffset = {
x: e.pageX - clickedDiv.x() - $().playground().offset().left,
y: e.pageY - clickedDiv.y() - $().playground().offset().top
};
});
$(".gQ_sprite").mouseup(function() {
clickedDiv = false;
});
$().playground().mousemove(function(e) {
if(clickedDiv){
clickedDiv.xy(
e.pageX - clickedDivOffset.x,
e.pageY - clickedDivOffset.y,
);
}
});
This will implement a drag-n-drop effect. If you want the clicked element to stick to the mouse you will have to slightly adapt the code but the basics will remain the same.
According to the documentation:
If the mouse tracker is enabled you can check the state of the mouse at anytime by looking into the object $.gQ.mouseTracker where x and y contain the position of the mouse and 1, 2 and 3 a boolean value where true means that the first, second or thrid button is pressed.
Observe the output of:
$("#playground").playground({ refreshRate: 60, mouseTracker: true });
$.playground().startGame();
$.playground().registerCallback(function(){
console.log( $.gQ.mouseTracker );
}, 1000);
To make those divs actually follow the cursor, you have to use .css()
$('#' + currentClickedDivId).css({
top: $.gQ.mouseTracker.y + 'px',
left: $.gQ.mouseTracker.x + 'px'
});

How to update X and Y coordinate when hovering an object

I have an image that changes position when I click inside a div like this:
mainDiv.click(function (e) {
var mouseX = e.clientX,
mouseY = e.clientY;
test2 = Math.atan(mouseY/mouseX);
test3 = ((test2 * 180) / 3.14);
$("#hgun").rotate(test3);
});
But it only changes position when I click inside the div. How can I make it change position when I hover inside the div ?
The .hover() method binds handlers for both mouseenter and mouseleave events. You can use it to simply apply behavior to an element during the time the mouse is within the element.
It is called like this:
$(selector).hover(handlerIn, handlerOut)
Which is short for:
$(selector).mouseenter(handlerIn).mouseleave(handlerOut);
In your case that would be:
mainDiv.hover(function (e) {
var mouseX = e.clientX,
mouseY = e.clientY;
test2 = Math.atan(mouseY / mouseX);
test3 = ((test2 * 180) / 3.14);
$("#hgun").rotate(test3);
},
function (e) {
//On mouseleave
});
Further read: jQuery hover documentation, jQuery mouse events
Update, based on author's comment:
I am not sure what exactly you are trying to achieve, but if you want your calculation and the related actions to be made every time the mouse moves within the container, you can use the mousemove event.
I've done a simple Fiddle based on your code, check it out: http://jsfiddle.net/sQ4Z4/1/
I used the first jQuery Rotate Plugin I found, which might not be the one you used, but it should be enough to get you in the right direction.
Basically your code should look something like this:
mainDiv.mousemove(function (e) {
var mouseX = e.clientX,
mouseY = e.clientY;
test2 = Math.atan(mouseY / mouseX);
test3 = ((test2 * 180) / 3.14);
$("#hgun").rotate(test3);
});
Change this line:
mainDiv.click(function (e) {
to
mainDiv.hover(function (e) {
hover accepts two functions: The first is executed on mouseenter, the second on mouseleave.

Apply jQuery events to all class elements?

I have the following code which will allowed a user running iOS to move a <div> with the class .drag around on the page. This works fine when there is one istance of .drag, but fails to work when there are two instances of it. Is it possible to have the code find all of the <div>'s, then allow them to be draggable?
var drag = $(".drag")[0];
xPos = drag.offsetWidth / 2;
yPos = drag.offsetHeight / 2;
drag.addEventListener("touchmove", function() {
event.preventDefault();
$(this).css({
'left' : event.targetTouches[0].pageX - xPos + 'px',
'top' : event.targetTouches[0].pageY - yPos + 'px'
});
});
When you use $(selector)[0], you get the first DOM element that matches the selector. Use .each() instead to add the event listener to all elements that match the selector:
$(".drag").each(function () {
var drag = this;
xPos = drag.offsetWidth / 2;
yPos = drag.offsetHeight / 2;
drag.addEventListener("touchmove", function() {
event.preventDefault();
$(this).css({
'left' : event.targetTouches[0].pageX - xPos + 'px',
'top' : event.targetTouches[0].pageY - yPos + 'px'
});
});
});​
Yes, it's possible. But you are using a jQuery selector (which can select and return multiple elements) and then immediately unwrapping it to return the first element. You can modify your code to use jQuery functions throughout and avoid this.
// an array of all elements with class "drag"
// each element is wrapped
var drag = $(".drag");
// selects all matching elements, but then references
// the first raw DOM element in the array
var drag = $(".drag")[0];
Another way of looking at it:
var matches = $(".drag");
// each() executes a function for each matched element
matches.each(function () {
var drag = this; // raw dom element
// or, wrap to get jQuery object
// var drag = $(this);
});​
As I mentioned, you can also use jQuery functions throughout your code. Two quick examples I see are the x/y coordinate calculation and the event binding.
First, you declare that you want only the first element by using [0].
Second, you should use jQuery's on() method. Here's how I see you function:
var drag = $(".drag");
drag.on("touchmove", function(event) {
xPos = $(this).offsetWidth / 2;
yPos = $(this).offsetHeight / 2;
event.preventDefault(); // preventDefault is IE-specific, is it?
$(this).css({
'left' : event.targetTouches[0].pageX - xPos + 'px',
'top' : event.targetTouches[0].pageY - yPos + 'px'
});
});
This is probably obvious to most experienced devs, but could be helpful to some junior devs who like myself have had trouble getting jQuery to apply to multiple elements.
Today I learned that you have to make sure you’re loading your script outside the div itself.
I was mistakenly loading the script inside the first element, and wondering why the jQuery function wasn’t applying to the other div farther down the page.
Screenshot showing < script > inside parent < div >
^ I was doing it wrong

How to create a 2D grid in webpage?

How can I create a grid (10X10) in a webpage and allow an user to click any position in the grid and recording the (x,y) position in one-decimal approx such as covering the values 0.0~10.0 or 0.1~9.9?
Thanks!
Use a <canvas> for the grid, and attach a click event listener.
You can record mouse clicks using the clientX and clientY properties of the mouse event object:
document.addEventListener('click', function(event){event.clientX;event.clientY;}, false);
The above code is just a demonstration, it isn't even cross browser compatible. event.clientX and event.clientY hold the mouse coordinates.
demo
I used the jQuery library.
var boxX = 0;
var boxY = 0;
var box = '<div class="box" />'; // define the .box element
for(var i = 0; i<100;i++){ // create 100 boxes
$('#grid').append(box);
}
$('.box').on('click',function(){
boxX = $(this).position().left;
boxY = $(this).position().top;
$(this).text('X='+ boxX +' , Y='+ boxY);
});
Instead of .position() (to get the element position from the parent element) you can use .offset() to get the element offset from window boundaries.

Categories

Resources