javascript - how to write a function in jquery -


this question has answer here:

guys want write code shortly, instead of rewriting same code 4 elements individually write function called each element , execute.

$(function(){ $('#basic').mouseover(function(){     $('#table-one').css({ boxshadow : "0 0 5px 3px rgba(100,100,200,0.4)" });     }); $('#basic').mouseout(function(){     $('#table-one').css({ boxshadow : "0 0 0 0" });     });  });  $(function(){ $('#standard').mouseover(function(){     $('#table-two').css({ boxshadow : "0 0 5px 3px rgba(100,100,200,0.4)" });     }); $('#standard').mouseout(function(){     $('#table-two').css({ boxshadow : "0 0 0 0" });     });   });      $(function(){ $('#pro').mouseover(function(){     $('#table-three').css({ boxshadow : "0 0 5px 3px rgba(100,100,200,0.4)" });     }); $('#pro').mouseout(function(){     $('#table-three').css({ boxshadow : "0 0 0 0" });     });  });    $(function(){ $('#expert').mouseover(function(){     $('#table-four').css({ boxshadow : "0 0 5px 3px rgba(100,100,200,0.4)" });     }); $('#expert').mouseout(function(){     $('#table-four').css({ boxshadow : "0 0 0 0" });     });  }); 

you should add data attribute markup, linking triggering element (#standard etc) table want hilight. in general, it's wise semantically link related elements code can generic possible, , apply wide range of elements on page:

<div id="standard" data-table="#table-one"> ... </div> 

now, of elements can use same handlers:

$(function () {    $('#basic, #standard, #pro, #expert').mouseover(function () {     $($(this).data("table")).css({ boxshadow : "0 0 5px 3px rgba(100,100,200,0.4)" });   }).mouseout(function () {     $($(this).data("table")).css({ boxshadow : "0 0 0 0" });   });  }); 

note: don't need wrap each , every block in $(function () { }). one, around whole blob of code posted, suffice.


Comments