Henry Aspden
Henry Aspden

Reputation: 1945

change background image in CSS when clicked

Please can somebody tell me how to do the following

.logo {
display: block;
text-indent: -9999px;
text-transform: capitalize;
background: url(../images/menu.png) no-repeat;
height: 120px;
}

change image so when its clicked

background: url(../images/menu_open.png) no-repeat;

the HTML for this is

<div class="sidebar">
<a href="#" onclick="return showOrHide('menulink');"><div class="logo">TEST IMAGE</div></a>
<ul id="menulink">

Currently when clicking the icon, the menu opens and closes,

view the full codes at http://carbonyzed.co.uk/menu/2/index.html http://carbonyzed.co.uk/menu/2/css/style.css

Thanks

Upvotes: 0

Views: 3169

Answers (3)

daveyfaherty
daveyfaherty

Reputation: 4613

For the best user experience, consider using a sprite, and changing the class on click, rather than changing the style attribute. So imagine you have the two images in one sprite, called menu_sprite.png

The image is 240px high, and the width of the logo. The default image is in top left, the "open" image is right underneath.

CSS

.logo{
  background-image: url(../images/menu_sprite.png) 0 0 no-repeat;
}

.logo.open{
  background-position: 0 -120px;
}

jQuery

$('.logo').click(function(){ $(this).toggleClass('open'); });

This method lets you avoid having a split-second with no image, without using preloaders.

Upvotes: 1

Lowkase
Lowkase

Reputation: 5699

$(".logo").click(function() {
  $(this).css('background-image', 'url(../images/menu_open.png)');
});

Upvotes: 3

pmeyer
pmeyer

Reputation: 890

This should work

<a href="#" onclick="return ShowOrHide('menulink'); document.getElementById('id').style.background = 'url(img.img) no-repeat';" />;

Upvotes: 0

Related Questions