user3801329
user3801329

Reputation: 17

Changing background image on click (jQuery)

I was wondering if anyone could tell me why this isn't working. I just want the background image to change when the div (with id "el") is clicked. It should change from "elephant coloured1" to "elephant coloured2" but its not working. Any help would be appreciated. Thanks :)

The HTML:

<body>
    <div id = "el"> </div>
</body>
</html>

And the jQuery:

$(document).ready( function() {
  $('#el').click(function() {
     $(this).css("background-image", 'url(elephant coloured2.svg)'); 
  });
});

And the CSS:

#el {
    background-image: url("elephant coloured1.svg");
    height: 190px;
    width: 250px;
}

Upvotes: 1

Views: 169

Answers (5)

Sudheer
Sudheer

Reputation: 2985

try with background instead of background-image

fiddle

.el {
  background-image: url("elephant coloured1.svg");
  height: 190px;
  width: 250px;
  z-index:-1;
}
.el1 {
  background-image: url("elephant coloured2.svg");
  height: 190px;
  width: 250px;
}

$(document).ready( function() {
  $('#el').click(function() {
  $(this).toggleClass('el1');
});

have them as classes. and use toggle class.

Problem might be your z-index.

or just try

#el {
  background-image: url("elephant coloured1.svg");
  height: 190px;
  width: 250px;
  z-index:-1;
}

Upvotes: 2

Morgan Feeney
Morgan Feeney

Reputation: 897

Perhaps your image url needs a dash or underscore instead of a space, like this: elephant-coloured2.svg not like this: elephant coloured2.svg

Upvotes: 0

Ajay Parsana
Ajay Parsana

Reputation: 175

Are you executing on Chrome? Try on Mozilla and try with below code.

<body>

<div id = "el"> Click Me!!! </div>

</body>

</html>

and Query

$(document).ready( function() {



                $('#el').click(function() {
                    $(this).css("background-image", 'url("elephant coloured2.svg")'); });

});

Your CSS is fine.

Upvotes: 0

Avisek Chakraborty
Avisek Chakraborty

Reputation: 8299

Seems issue with your SVG image- because exact your code is working fine here-

http://jsfiddle.net/7fJVa/2/

$(document).ready( function() {
     $('#el').click(function() {
         $(this).css("background-image", 'url(https://www.google.co.in/images/srpr/logo11w.png)');
     });

});

Or Jquery might not properly attached. Check for Console for JS errors.

Upvotes: 1

T J
T J

Reputation: 43156

try

$('#el').click(function() {
  $(this).css("background-image", 'url("elephant coloured2.svg")');
});

with the quotes.

Upvotes: 3

Related Questions