Reputation: 22879
I'm writing a function which requires knowing the location of the clicked div.
I'm wondering if I can get the location of a clicked object as a javascript variable?
here is the code.
HTML
<area shape="rect" coords="103, 0, 213, 25" href="#" onClick="swap3($(this),'product-details','product-specs');">
Javascript:
function swap3(currentDivId ,oldDivId, newDivId) {
var oldDiv = currentDivId.nextAll("div." + oldDivId);
var newDiv = currentDivId.nextAll("div." + newDivId);
oldDiv.style.display = "none";
newDiv.style.display = "block";
}
Upvotes: 1
Views: 113
Reputation: 27585
$()
returns a DOM element (like an object that you can work with it's methods, properties, etc) and if you set a variable to it, the variable must work like an jQuery-Object correctly. But in my experience, some times that DO NOT! and I learn the best way is to get the variable by jQuery-selector ($
). Your code is correct, but should be better if you apply these changes:
function swap3(currentDivId ,oldDivId, newDivId) {
var oldDiv = $(currentDivId).nextAll("div." + oldDivId);
var newDiv = $(currentDivId).nextAll("div." + newDivId);
$(oldDiv).css({"display" : "none"});
$(newDiv).css({"display" : "block"});
}
Upvotes: 0
Reputation: 15802
this
refers to the current element.
In jQuery, as they use $()
to get an element, $(this)
returns the jQuery equivalent of vanilla JS's this
.
<area shape="rect" coords="103, 0, 213, 25" href="#" onClick="swap3(this,'product-details','product-specs');">
Upvotes: 3