Sony ThePony Sony ThePony - 6 months ago 17
Javascript Question

Please help me simplify the following code

Can anyone assist me in simplifying this working piece of jQuery? I've heard that forEach could help me there, but don't know how to use it.


$("div#accordion .panel:nth-child(1)").click(function(){
$(".changer .vc_column-inner").css("cssText", "background-image: url(wp-content/uploads/2016/04/WLDMCHPLAY-QF-FANS1-e1469784860667.jpg) !important;");

$("div#accordion .panel:nth-child(2)").click(function(){
$(".changer .vc_column-inner").css("cssText", "background-image: url(wp-content/uploads/2016/04/mountains-snow-cars-bentley-roads-vehicles-bentley-continental-bentley-continental-gt-front-angle-vi-2015.jpg) !important;");

$("div#accordion .panel:nth-child(3)").click(function(){
$(".changer .vc_column-inner").css("cssText", "background-image: url(wp-content/uploads/2016/04/1007.jpg) !important;");



You can simplify it using an array. Store the CSS property value in an array and update value based on element index (index can be get using index() method).

jQuery(document).ready(function($) {
  // store URLs in an array for selecting based on the index
  var css = [
    "url(wp-content/uploads/2016/04/WLDMCHPLAY-QF-FANS1-e1469784860667.jpg) !important;",
    "url(wp-content/uploads/2016/04/mountains-snow-cars-bentley-roads-vehicles-bentley-continental-bentley-continental-gt-front-angle-vi-2015.jpg) !important;",
    "url(wp-content/uploads/2016/04/1007.jpg) !important;"
    // store the reference to the element for future reference 
  $ele = $("div#accordion .panel").click(function() {
    // get the css value based the index of clicked element
    // with help of referenced variable , here index means the position within the referenced selector
    // where `this` refer to the clicked element
    $(".changer .vc_column-inner").css("background-image", css[$ele.index(this)]);