Brian Cortright Brian Cortright - 3 months ago 18
jQuery Question

Simplify Multiple Functions for Similar Elements

I'm really new to jQuery, and after looking around in different threads I still can't seem to figure this out. Hoping someone out there is kind enough to break this down for me with kid gloves.

I'm trying to figure out how to simplify multiple functions to achieve different popups for different, but similar elements.

Here's what it currently looks like:

$("#cooper_link").click(function(e){
e.preventDefault();
$("#cooper_overlay").fadeIn(500);
$("#cooper_popup").fadeIn(500,function(){$(this).focus();});
});

$("#quentin_link").click(function(e){
e.preventDefault();
$("#quentin_overlay").fadeIn(500);
$("#quentin_popup").fadeIn(500,function(){$(this).focus();});
});

$("#jasper_link").click(function(e){
e.preventDefault();
$("#jasper_overlay").fadeIn(500);
$("#jasper_popup").fadeIn(500,function(){$(this).focus();});
});

$("#jordan_link").click(function(e){
e.preventDefault();
$("#jordan_overlay").fadeIn(500);
$("#jordan_popup").fadeIn(500,function(){$(this).focus();});
});

$("#james_link").click(function(e){
e.preventDefault();
$("#james_overlay").fadeIn(500);
$("#james_popup").fadeIn(500,function(){$(this).focus();});
});

$("#liam_link").click(function(e){
e.preventDefault();
$("#liam_overlay").fadeIn(500);
$("#liam_popup").fadeIn(500,function(){$(this).focus();});
});

$('.close').click(function() {
$("#cooper_overlay, #quentin_overlay, #jasper_overlay, #jordan_overlay, #james_overlay, #liam_overlay").fadeOut(500);
$("#cooper_overlay, #quentin_overlay, #jasper_overlay, #jordan_overlay, #james_overlay, #liam_overlay").fadeOut(500);
});

$("#cooper_popup").on('blur',function(){
$("#cooper_overlay").fadeOut(500);
$(this).fadeOut(500);
});

$("#quentin_popup").on('blur',function(){
$("#quentin_overlay").fadeOut(500);
$(this).fadeOut(500);
});

$("#jasper_popup").on('blur',function(){
$("#jasper_overlay").fadeOut(500);
$(this).fadeOut(500);
});

$("#jordan_popup").on('blur',function(){
$("#jordan_overlay").fadeOut(500);
$(this).fadeOut(500);
});

$("#james_popup").on('blur',function(){
$("#james_overlay").fadeOut(500);
$(this).fadeOut(500);
});

$("#liam_popup").on('blur',function(){
$("#liam_overlay").fadeOut(500);
$(this).fadeOut(500);
});


Here's a CodePen for the full thing:

http://codepen.io/chubbaluv/pen/GqZwjE

Answer

Simple solution based on your markup.. of course there are more ways of doing this but not sure how much control u have over the markup

$(".rider").click(function(e){
e.preventDefault();
// get the link id
var linkid = this.id
// get the unique part of the section
var id = linkid.replace("_link","");
// since all the elements have this part in their name, use it
$("#"+id+"_overlay").fadeIn(500);
  $("#"+id+"_popup").fadeIn(500, function() {
    $(this).focus();
  });

});
Comments