Daniel Edwards
Daniel Edwards

Reputation: 163

Can i add class to a different element of hover with jquery/js

i have mutable elements with different id and want to match the id name with the class on the A tag then toggle a class to the a tag`

    <a id="AB" href="" class="divone marker"><span>This is ab</span></a>
    <a id="ABA" href="" class="divtwo marker"><span>This is aba</span></a>
    <a id="ABAB" href="" class="divthree marker"><span>This is abab</span></a>

<div id="divone"></div>
<div id="divtwo"></div>
<div id="divthree"></div>

when i hover over the div it gets the ID then matches it to the class on the a tag and adds class active and when i remover the hover it removes the class

I hope this makes sense and any help would be much appreciated

Thanks in advance Dan

Upvotes: 0

Views: 593

Answers (3)

You can use jQuery.hover()

http://jsfiddle.net/4snhdpx1/6/

$('div').hover(function(event) {
    if (event.type == 'mouseenter') {
        $('.' + this.id).addClass('active');
    } else {
        $('.' + this.id).removeClass('active');
    }
});

And just for fun you can use shorter code :)

http://jsfiddle.net/4snhdpx1/8/

$('div').hover(function(e) {
    $('.' + this.id)[e.type == 'mouseenter' ? 'addClass' : 'removeClass']('active');
})

Upvotes: 1

Thomas Theunen
Thomas Theunen

Reputation: 1274

You can do it like this with jQuery.

$('a').on('mouseenter', function() {
  var classList = $(this).attr('class').split(/\s+/);
  $.each(classList, function(index, classname) {
    $('#' + classname).addClass('active');
  });
});

$('a').on('mouseleave', function() {
  var classList = $(this).attr('class').split(/\s+/);
  $.each(classList, function(index, classname) {
    $('#' + classname).removeClass('active');
  });
});
.active {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="AB" href="" class="divone marker"><span>This is ab</span></a>
<a id="ABA" href="" class="divtwo marker"><span>This is aba</span></a>
<a id="ABAB" href="" class="divthree marker"><span>This is abab</span></a>
<br />
<div id="divone">one</div>
<div id="divtwo">two</div>
<div id="divthree">three</div>

Upvotes: 0

Tom
Tom

Reputation: 195

I wrapped the divs in another container to have an easier access.

$('#container > div').on('mouseenter', function(){
    var $el = $('.' + $(this).attr('id'));
    $el.addClass('active');
});
$('#container > div').on('mouseleave ', function(){
    var $el = $('.' + $(this).attr('id'));
    $el.removeClass('active');
});

https://jsfiddle.net/s9628o2y/

Upvotes: 0

Related Questions