Jquery get specific *instance of the class* that triggered an event - javascript

I am working on a game in which JSON data is turned into a bunch of classes that are painted on top of the main map. Each icon is a small 20x20 pixel box. Moving the cursor over each box is then meant to change another div's html to relay the information "hidden" inside of each class's value.
My code goes like this:
$('.City_Palace').mousemove(function(e) {
e.stopPropagation();
var x = Math.floor((e.pageX - this.offsetLeft + $("#scrollWindow").scrollLeft()) / tileSize);
var y = Math.floor((e.pageY - this.offsetTop + $("#scrollWindow").scrollTop())/tileSize);
var text = $('#WorldMapMessage').html();
alert(e.target.className);
$('#WorldMapMessage').html(x +', '+ y + " " + $(this).val());
// alert($(this).val());
});
This code currently brings up an alert box with the classname of what caused the event. However, what I need to know is which precise instance of the .City_Palace class triggered the event so I can display the appropriate text. If I were using ids instead of classes, this would be trivial, but for this I need to use classes and know which one is invoking the event.
Thanks for the help!

You already seem to be doing this.
Inside the function you pass into .mousemove(), you have access to this, which refers to the specific instance of the element that's being hovered on. You can use it to get anything else you might need from that specific instance of the element. For example:
$('.City_Palace').mousemove(function(e) {
// $(this) is the specific instance of .City_Palace that's being hovered on.
alert($(this).attr("class")); // Alert the class name.
});

Related

On div hover, return it's left attribute

I have 50 divs that have all the same class (.marker), and an id (#a1, #a2, ...).
Now I want, that if I hover over such a div a JavaScript function is called that returns the css-left attribute of the specific div:
function(divId){
return $(divId).css("left");
}
And I don't know how to do that without having to write a function call to every div.
I thought of something with this.css("left"), that saves me typing work.
Thanks for your help in Advance...
You can't return a value from a click handler. But, you can change your approach to changing a variable
var currentLeft;
$('.marker').hover(function(){
currentLeft = $(this).css('left');
});

How can I invisiblize groups of controls via jQuery?

In my Sharepoint project/Web Part/Web Page, I dynamically create page elements/controls using C# in the *.ascx.cs file.
In the *.ascx file, I use jQuery for responding to events that happen on the page (selections, changes of checkbox states, etc.).
I have a need to conditionally invisiblize groups of controls/elements on the page. Specifically, if the user checks a certain checkbox, I can "remove" whole swaths of the page that, in that scenario, don't apply to her.
How can I do this? I've got this starting point:
/* If the select "Yes" (they are seeking payment for themselves, as opposed to someone else), omit (invisibilize) sections 2 and 3 on the form */
$(document).on("change", '[id$=ckbxPaymentForSelf]', function () {
var ckd = this.checked;
if (ckd) {
// what now?
}
});
I could do it the hair-pulling-out way (which would be very painful for me, because I have almost as much hair as Absalom did), and set each individual element, like so:
if (ckd) {
var $this = $('[id$=txtbxthis]');
var $that = $('[id$=txtbxthat]');
var $theother = $('[id$=txtbxtheother]');
. . . // store a reference to all the other to-be-affected elements in vars
$this.visible = false; // <= this is pseudoscript; I don't know what the jQuery to invisiblize an element is
$that.visible = false; // " "
$theother.visible = false; // " "
. . . // invisiblize all the other to-be-affected elements
}
Surely there's a more elegant/better way!
Is it a matter of assigning all the conditionally invisible elements a particular class, and then invisiblizing every element that is assigned that class, or what?
Also, I want the area formerly used by this now-invisible swath to "go away" or "roll up" not sit there with a blank stare, yawning chasm, or Gobi Desert-like featureless expanse.
there are a number of ways to do this. but in your jquery implementation I would decorate the elements with data tags that will tell the code which elements to hide and show.
<input data-group="1" type="text" />
<input data-group="2" type="text" />
var $group1 = $('*[data-group="1"]');
var $group2 = $('*[data-group="2"]');
if (ckd) {
$group1.hide();
$group2.show();
}
else{
$group2.hide();
$group1.show();
}
You could do the same thing with css classes as well but I prefer using the data attribute
If you can group your controls using classes, you could select the class which needs to be hidden in that particular scenario and just use the hide() function:
if (ckd) {
var cls = getClassForCurrentScenario();
$("." + cls).hide(); //slideUp() would be an animated alternative
}
If the controls can be grouped inside a div, for example, then you'd just need to hide that element:
if (ckd) {
var id = getElementIdForCurrentScenario();
$("#" + id).hide(); //slideUp() would be an animated alternative
}
It really depends on how you manage to group your controls into "target groups", so that you can efficiently access them later.
You can hide an element like so:
$('...').hide();
Or you can slide it up with:
$('...').slideUp();
to get a nice sliding up animation.
On a side note, you can do this to multiple elements at once, in your case:
$('[id$=txtbxthis], [id$=txtbxthat], [id$=txtbxtheother]').slideUp();

How to calculate each element's height and use these values as a variable in function?

I am trying to create a simple text accordion which calculates each panel's height and return this value as a variable. I can get values with if statements like if ( i === 0 ) { $(this).height(); } but can't get this variable to the outside.I can do this without using variable but it became useless in long term.
Brıefly: I want to calculate each element's height and use this variable inside click function.
Here is jsFiddle which includes the problem.
var panel = $('.holder div');
var trigger = $('a');
panel.each(function(i) {
//problem starts when i try to calculate each ele's height
var eachEleHeight = i.height();
trigger.click(function() {
$(this).prev('div').animate({'height':eachEleHeight+'px'},500);
//this works widthout var eachEleHeight but became useless
//$(this).prev('div').animate({'height':'300px'},500);
});
//this is for hiding text at doc.ready
panel.css('height','56px');
});​
If I well understood, try this :
panel.each(function(i, el) {
// create a reference to te current panel
var $el = $(el);
// execute a function immediately, passing both the panel and its height
(function(p, h) {
// the trigger is targeted as the next link after the current panel
p.next('a').click(function() {
p.animate({ height : h + 'px'},500);
});
}($el, $el.height()));
// set each panel height
$el.css('height','56px');
});
Example fiddle : http://jsfiddle.net/Aw39W/55/
There is a problem with the code you posted. i is the index of the current element. Not the element itself.
Try var eachEleHeight = $(this).height();
Fiddle
The sequence of events you've used seems a bit weird. You're actually binding a click event to all a tags for each panel element. Try this: Fiddle
I just used the min-height and max-height css attributes to store the initial to/from height variables. This will automatically get you your starting heights.
If I understand the question, you want to have the elements height for the accordion animation function. This is a trick but it works. I frequently use Mootools so I'll write using it. You should be able to figure it out.
var orgHeight = i.offsetHeight;
i.setStyle('height','100%');
var eachEleHeight = i.offsetHeight;
i.setStyle('height',orgHeight);
Essentially you would be flipping the element to reveal it's height and flipping it back before the document has time to make it visible on screen.
Not sure this is exactly what you were looking for, but hope it helps.

Get id of selected element

I'm trying to find a way to get the element id of the currently hovered element to show a popup box / tooltip. At the moment I'm using clientX / clientY to get coordinates but I would really like the popup to be centered over the element I'm hovering.
Is there some way to get this information, for example "who called show_tooltip" or similar to later get the coordinates of the element. Hope this makes sense.
In response to the comment below, this is what I'm currently using.
function show_tooltip(evt) {
var x = evt.clientX -50;
var y = evt.clientY -70;
tooltip.setAttributeNS( null, "transform", "translate(" + x + "," + y + ")" );
tooltip.setAttributeNS( null, "opacity", "0.7" );
}
The problem with this is that the mouse pointer is used for coordinates. While I can use getElementById() to get an element, I do not know which element that called the function.
I don't know if this is what you're looking for:
<div onmouseover="show_tooltip(this)"/>
And you will get the element that fired the event in the js function.
Maybe you could have a look at http://docs.jquery.com/Plugins/Tooltip (demo). Thoose kinds of plugins have already been developed a lot of times. This one is just an example.
Event.target (in your script evt.target) holds the target of the event (an element typically).

Mouse Click coordinates - a true solution ... is there one?

There are, as of now, 3,898 posts in StackOverflow regarding mouse click coordinates. They all cover everything on how to find the coordinates for the mouse .... in relation to an element.
Has anyone been able to implement a solution where, at any point of your processing, you can recall the coordinates of the very last mouse click?
I have tried everything and every solution for the last 8 hours or so but cannot come accross anything that can recall the last mouse click coordinates.
Apparently, you have to catch it right where you are processing $('...').click(function(e){...});
How about if I sent the processing somewhere and, within that processing (a few nanoseconds later) I want to find out the coordinates of the last mouse click? How can I retrieve it outside an specific function?
EDIT:
Based on sdleihssirhc's suggestion, I was able to implement a solution that is working for me:
On the main page I have created two divs (to avoid dealing with arrays and global variables):
<div id='mouseX' style='display:none; ' ></div>
<div id='mouseY' style='display:none; ' ></div>
On the main page within the script tags:
$('#wrapper').click(function(e) {
var offset = $(this).offset();
$('#mouseX').text(e.clientX - offset.left);
$('#mouseY').text(e.clientY - offset.top);
});
Whenever needed, I can just:
var clickX = $('#mouseX').text();
var clickY = $('#mouseY').text();
Thank you!
You can set up a global array, for keeping track of coordinates (maybe in an object, whatever). Then you can add an event listener to the document, listening for click. Then it's just a matter of logging the position.
Whenever you want to refer to the position during the last click, just refer to the appropriate element of your global array. (If your logging function unshifted instead of pushing, you could always just look at yourArray[0].)
In the $('...').click(function(e){...}); handler, you can set a global variable with the coordinates. For example:
Globally:
var x = -1, // no previous click
y = -1; // no previous click
In the click handler:
x = e.pageX();
y = e.pageY();
Then, you can just reference x and y when you need the coordinates of the last click.

Categories

Resources