Shawn
Shawn

Reputation: 1372

looking for a more efficient way to write this jquery

This code works as is but I'm looking for a more efficient way to write this jquery code. The goal of the code, when a show is selected(clicked) the display div will display show details when the next show is clicked it replace the details of the previously selected show in the display div.

/*jslint browser: true*/
/*global $, jQuery, alert*/
$(document).ready(function () {
    "use strict"; 
    $('#shows_morning_news').click(function () {
    $('#shows_info_display').html($('#display_morning_news').html());
    });
    $('#shows_danielle_smith').click(function () {
    $('#shows_info_display').html($('#display_danielle_smith').html());
    });
    $('#shows_rob_breakenridge').click(function () {
    $('#shows_info_display').html($('#display_rob_breakenridge').html());
    });
    $('#shows_calgary_today').click(function () {
    $('#shows_info_display').html($('#display_calgary_today').html());
    });
    $('#shows_sports_talk').click(function () {
    $('#shows_info_display').html($('#display_sports_talk').html());
    });
    $('#shows_charles_adler').click(function () {
    $('#shows_info_display').html($('#display_charles_adler').html());
    });
});

Upvotes: 0

Views: 42

Answers (2)

Ananth Cool
Ananth Cool

Reputation: 135

You may use you current id value to achieve it. Check the below code.

$(document).on("click",function(){
    var id = $(this).attr("id");
    if(id.search("shows") == 0){
        var requiredIdPart = id.replace("shows","");
        $("#shows_info_display").html($("#display"+requiredIdPart).html());
    }
});

Upvotes: 0

Dan Kreiger
Dan Kreiger

Reputation: 5516

You could try this:

/*jslint browser: true*/
/*global $, jQuery, alert*/
$(document).ready(function() {
  "use strict";
  [
    "morning_news",
    "danielle_smith",
    "rob_breakenridge",
    "calgary_today",
    "sports_talk",
    "charles_adler"
  ].map(function(id) {
    $("#shows_" + id).click(function() {
      $("#shows_info_display").html($("#display_" + id).html());
    });
  });
});

CodePen Demo

Upvotes: 1

Related Questions