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
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');
});
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>
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');
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.