probablybest probablybest - 1 month ago 15
Javascript Question

Add number to end of div with jQuery

I'm using jQuery to create a simple addClass on hover. Hovering over a

#science-panel-number
div triggers a class of
.active
to be added to an
#iphone-screen-number
div.

Here is my jQuery:

$('#science-panel-1').hover(function(){
$('#iphone-screen-1').addClass('active');
},function(){
$('#iphone-screen-1').removeClass('active');
});

$('#science-panel-2').hover(function(){
$('#iphone-screen-2').addClass('active');
},function(){
$('#iphone-screen-2').removeClass('active');
});

$('#science-panel-3').hover(function(){
$('#iphone-screen-3').addClass('active');
},function(){
$('#iphone-screen-3').removeClass('active');
});


My HTML:

<div class="col-md-4">
<div id="science-panel-1" class="science-panel__item">
Content goes in here!
</div>
<div id="science-panel-2" class="science-panel__item">
Content goes in here!
</div>
<div id="science-panel-3" class="science-panel__item">
Content goes in here!
</div>
</div>

<div class="col-md-4">
div id="iphone-screen-1" class="iphone-screen-item">
<img src="IMG-url-here.jpg" alt="" />
</div>
div id="iphone-screen-2" class="iphone-screen-item">
<img src="IMG-url-here.jpg" alt="" />
</div>
<div id="iphone-screen-3" class="iphone-screen-item">
<img src="IMG-url-here.jpg" alt="" />
</div>
<div id="iphone-screen-4" class="iphone-screen-item">
<img src="IMG-url-here.jpg" alt="" />
</div>
<div id="iphone-screen-5" class="iphone-screen-item">
<img src="IMG-url-here.jpg" alt="" />
</div>
<div id="iphone-screen-6" class="iphone-screen-item">
<img src="IMG-url-here.jpg" alt="" />
</div>
</div>

<div class="col-md-4">
<div id="science-panel-4" class="science-panel__item">
Content goes in here!
</div>
<div id="science-panel-5" class="science-panel__item">
Content goes in here!
</div>
<div id="science-panel-6" class="science-panel__item">
Content goes in here!
</div>
</div>


This feels like a lot of code to do the same script. Is there a way to have one piece of script that can add the numbers it self? As
#science-panel-1
will always link to to
#iphone-screen-1
and so on.

Answer

This will do what you need. Just apply the handlers to elements whose ID begins with science-panel-, which should cover all of them...

$("[id^=science-panel-]").hover(function() {
    // get the corresponding iphone-screen element id
    var iphoneScreen = "#" + this.id.replace("science-panel-", "iphone-screen-");
    $(iphoneScreen).addClass("active");
},function() {
    var iphoneScreen = "#" + this.id.replace("science-panel-", "iphone-screen-");
    $(iphoneScreen).removeClass("active");
});
Comments