Randy Daniel
Randy Daniel

Reputation: 57

Pass dynamic id to be reused throughout function

I have a group of <p> elements with unique id's (#one-context, #two-context, #three-context). I'd like to reveal a corresponding div element (starts with "scale-" and ends with either "one", "two" or "three") when hovered over each <p> element.

Is it possible to write code, simple & short, so when each element is hovered, the wildcard(?) "one" "two" or "three" of the p element gets stored as it iterates through the group? Here is where I'm currently at:

$("p[id$='-context']").mouseover(function() {
  $("div[id^='scale']").addClass("active-badge");
}).mouseout(function() {
  $("div[id^='scale-']").removeClass("active-badge");
});


<div id="scale-one">1</div>
<div id="scale-two">2</div>
<div id="scale-three">3</div>

<p id="one-context">Context 1</p>
<p id="two-context">Context 2</p>
<p id="three-context">Context 3</p>

So, it's essentially saving the values of "one", "two" and "three".

Thanks, everyone.

Upvotes: 2

Views: 81

Answers (1)

Kirill Simonov
Kirill Simonov

Reputation: 8481

Try this example. Inside the mouseover function this is a hovered node. You get it's id, cut off the "-context" part and get the selector like "div[id='scale-one']"

$("p[id$='-context']").mouseover(function() {
  $("div[id='scale-" + $(this).attr("id").replace("-context", "") + "']")
    .addClass("active-badge");
}).mouseout(function() {
  $("div[id='scale-" + $(this).attr("id").replace("-context", "") + "']")
    .removeClass("active-badge");
});
.active-badge {
    color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="scale-one">1</div>
<div id="scale-two">2</div>
<div id="scale-three">3</div>

<p id="one-context">Context 1</p>
<p id="two-context">Context 2</p>
<p id="three-context">Context 3</p>

Upvotes: 1

Related Questions