Bharat Negi Bharat Negi - 4 months ago 10
CSS Question

Can any one make this jquery code small

I have created jquery code but this is very big. please can any make small and dynamic code.

Jquery code:-

$(document).ready(function () {
$('#menuone').hover(
function() {
$('.bg-imgsection').toggleClass('displayon');
$('#logo .log-bg').toggleClass('log-bg1');
}
);
$('#menutwo').hover(
function() {
$('.bg-imgsection2').toggleClass('displayon');
$('#logo .log-bg').toggleClass('log-bg1');
}
);
$('#menuthree').hover(
function() {
$('.bg-imgsection3').toggleClass('displayon');
$('#logo .log-bg').toggleClass('log-bg1');
}
);
$('#menufour').hover(
function() {
$('.bg-imgsection4').toggleClass('displayon');
$('#logo .log-bg').toggleClass('log-bg1');
}
);

});


here is jsfiddle demo

Answer

Use a common handler and use an object to refer the class based on id of the element.

$(document).ready(function() {
 // object for refering the class based on id
  var cls = {
    menuone: 1,
    menutwo: 2,
    menuthree: 3,
    menufour: 4
  };

  $('#menuone,#menutwo,#menuthree,#menufour').hover(function() {
    // generate classname using id and the object
    $('.bg-imgsection' + cls[this.id]).toggleClass('displayon');
    $('#logo .log-bg').toggleClass('log-bg1');
  });

});