jquery - Can I loop through an array to change and elements attributes on hover -


this seems little verbose, there better way of doing this? i'm using jquery change navigations aria attributes hidden=true hidden=false on hover (same expanded). i'm sure can done in far fewer lines of code i'm not quite sure how. can sense thousand eyes rolling, sorry guys i'm noob.

var navarray = ['#navitem1', '#navitem2', '#navitem3', '#navitem4', '#navitem5' ] $(navarray[0]).hover(function(){     $( navarray[0] + 'dd').attr('aria-expanded','true');     $( navarray[0] + 'dd').attr('aria-hidden','false'); }, function(){     $(navarray[0] + 'dd').attr('aria-expanded', 'false');     $(navarray[0]+ 'dd').attr('aria-hidden', 'true'); });      $(navarray[1]).hover(function(){     $( navarray[1] + 'dd').attr('aria-expanded','true');     $( navarray[1] + 'dd').attr('aria-hidden','false'); }, function(){     $(navarray[1] + 'dd').attr('aria-expanded', 'false');     $(navarray[1]+ 'dd').attr('aria-hidden', 'true'); });     $(navarray[2]).hover(function(){     $( navarray[2] + 'dd').attr('aria-expanded','true');     $( navarray[2] + 'dd').attr('aria-hidden','false'); }, function(){     $(navarray[2] + 'dd').attr('aria-expanded', 'false');     $(navarray[2]+ 'dd').attr('aria-hidden', 'true'); });      $(navarray[3]).hover(function(){     $( navarray[3] + 'dd').attr('aria-expanded','true');     $( navarray[3] + 'dd').attr('aria-hidden','false'); }, function(){     $(navarray[3] + 'dd').attr('aria-expanded', 'false');     $(navarray[3]+ 'dd').attr('aria-hidden', 'true'); });      $(navarray[4]).hover(function(){     $( navarray[4] + 'dd').attr('aria-expanded','true');     $( navarray[4] + 'dd').attr('aria-hidden','false'); }, function(){     $(navarray[4] + 'dd').attr('aria-expanded', 'false');     $(navarray[4]+ 'dd').attr('aria-hidden', 'true'); });   

use common class selector target specific element regarding element id, using thisinside hover() in/out handler:

$('.nav-item').hover(function (e) {     var toexpand = e.type === "mouseenter";     $('#' + this.id + "dd").attr({         "aria-expanded": toexpand,         "aria-hidden": !toexpand,     }); }); 

i guess intead of targeting id, use index, depending html markup.


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -