Marcus
Marcus

Reputation: 21

change background image with js on mouse over

I want to change the background image when the visitor goes over the item link but I don't get it to work.

$('.swap').on('mouseover', 'a', function() {
  var backgroundUrl = "https://xxxxxxxxx.online/afbeeldingen/" + $(this).data('background');
  $('.swap').css({
    'background-image': 'url(' + backgroundUrl + ')'
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="swap"></div>
<ul class="nav">
  <li><a href="#" data-background="easy-verwijderen.svg">item 1</a></li>
  <li><a href="#" data-background="easy-invite.svg">item 2</a></li>
  <li><a href="#" data-background="easy-install.svg">item 3</a> </li>
</ul>

Upvotes: 1

Views: 45

Answers (2)

Marc Elsendoorn
Marc Elsendoorn

Reputation: 1

Thanks thats what I'm looking for. Is there a way that when I click (not mouse over) it doesn't jump to the top? I can remove href="#" that seems to work but don't now of that is supported on different browsers?

Upvotes: 0

Penny Liu
Penny Liu

Reputation: 17408

I ended up solving it as follows:

$('.nav').on('mouseover', 'a', function() {
  var backgroundUrl = "https://source.unsplash.com/" + $(this).attr('data-background');
  $(".swap").attr("style", "background-image: url(" + backgroundUrl + ")");
});
.swap {
  height: 200px;
  width: 400px;
  border: 1px solid black;
  background-repeat: no-repeat;
  background-image: url('https://source.unsplash.com/juHayWuaaoQ/400x200');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="swap">div with background</div>

<ul class="nav">
  <li><a href="#" data-background="juHayWuaaoQ/400x200">Item 1</a></li>
  <li><a href="#" data-background="eWFdaPRFjwE/400x200">Item 2</a></li>
  <li><a href="#" data-background="eXHeq48Z-Q4/400x200">Item 3</a></li>
</ul>

Upvotes: 1

Related Questions