Could not replace "if" statement with "switch" statement in jquery
I have a page with several puppies puppies, so when the user clicks on the preview, the full image appears. This is the html:
<tr class="rowLicense">
<td class="bigPop licensePopUp" ><img src="images/license/license_1.jpg"></td>
<td class="bigPop licensePopUp2"><img src="images/license/license_2.jpg"></td>
<td class="bigPop licensePopUp3"><img src="images/license/license_3.jpg"></td>
</tr>
This is the if if script version:
$(".bigPop").click(function(){
if ($(this).is(".licensePopUp")){ //
$(".popupLicense").fadeIn();
}
else if ($(this).is(".licensePopUp2")) {
$(".popupLicense2").fadeIn();
}
else if ($(this).is(".licensePopUp3"){
$(".popupLicense2").fadeIn();
}
});
it works but it seems not optimal
I tried using "switch", this is the code:
$(".bigPop").click(function(){
var i = $(this).is();
switch (i) {
case (".licensePopUp"):
$(".popupLicense").fadeIn();
break;
case (".licensePopUp2"):
$(".popupLicense2").fadeIn();
break;
}
});
It doesn't work, I suppose I made some mistakes in defining "i" or maybe in operator declaration, but I can't find a clue.
PS Please don't blame me, I just started learning js, so I don't know a lot of obvious things.
source to share
You can just do it without any if
orswitch
$(".bigPop").click(function() {
var num = $(this).attr("class").replace(/.*licensePopUp(\d).*/, "$1");
$('.popupLicense' + (num ? num : '')).fadeIn();
});
What you did above is a number in the class and then concatenating it with that number, or just an empty string if the number is not a number. Alternatively, you can set a separate attribute data-*
and then use that.
source to share
You could greatly simplify your code if you used some kind of data attribute that would target a specific popup:
<td class="bigPop" data-target=".licensePopUp"><img src="images/license/license_1.jpg"></td>
<td class="bigPop" data-target=".licensePopUp2"><img src="images/license/license_2.jpg"></td>
<td class="bigPop" data-target=".licensePopUp3"><img src="images/license/license_3.jpg"></td>
And then JS:
$(".bigPop").click(function () {
$($(this).data('target')).fadeIn();
});
This approach offers additional flexibility because it data-target
can now be any CSS selector, not just a class name, but also an id, etc.
source to share
How about this? I tried using event.target .
$(".bigPop").click(function(event){
var target = $( event.target );
target.fadeIn();
});
Note. I haven't tested the code yet.
source to share