The following code is for a vertical menu, where I needed a marker to slide down next to a link upon hovering over said link. Therefore I needed to change CSS properties of a HTML element (the top-margin in this case).
What I've done in jQuery is add a class ('.movedown1' or '.movedown2') to the marker div ('#slide') when the mouse hovers over one of the links ('#menulink2' or '#menulink3'), and remove the class when the mouse stops hovering over the link.
It works!...But is it a clean method to add/change CSS properties of a HTML element? Does it follow best practices for jQuery? I've only used jQuery a few times in the past so I'm not familiar with best practices.
HTML(Pug):
#slide
#menu
a.menulink#menulink1(href="#")
p RED
a.menulink#menulink2(href="#")
p BLUE
a.menulink#menulink3(href="#")
p GREEN
CSS (Sass)
a
color: white
text-decoration: none
#slide
width: 10px
height: 30px
background-color: red
position: absolute
border-radius: 15px
transition: 0.3s ease-in-out
.movedown1
margin-top: 40px
background-color: blue !important
.movedown2
margin-top: 80px
background-color: green !important
#menu
margin-left: 30px
.menulink
height: 40px
width: 70px
display: block
.menulink p
height: 30px
width: 70px
margin: 0px
border-radius: 15px
display: flex
align-items: center
justify-content: center
#menulink1 p
background: red
#menulink2 p
background: blue
#menulink3 p
background: green
jQuery
$('#menulink2').hover(
function(){
$('#slide').addClass('movedown1');
},
function(){
$('#slide').removeClass('movedown1')
});
$('#menulink3').hover(
function(){
$('#slide').addClass('movedown2');
},
function(){
$('#slide').removeClass('movedown2')
});