user2640633
user2640633

Reputation:

css and/or javascript change background on clicking image

I have an issue where I have a div class="tasteTheRainbow" and inside are img tags. One tag in particular is a png class named .gA3.

Now tasteTheRainbow already has a css background url but when you tap or click the .gA3 I want the background url to change.

I have tried many other stackoverflow posts and found no solution.

Here is my HTML and my CSS:

<div class="tasteTheRainbow">
    <div class="greenArrow">
        <img class="gA1" src="assets/arrows/down.png"/>
        <img class="gA2" src="assets/arrows/in.png"/>
        <img class="gA3" src="assets/arrows/left.png"/>
        <img class="gA4" src="assets/arrows/out.png"/>
        <img class="gA5" src="assets/arrows/right.png"/>
        <img class="gA6" src="assets/arrows/up.png"/>
    </div>
</div>
.tasteTheRainbow {
    background-image: url(../assets/fivePix.png);
    background-repeat: repeat;
    position: absolute;
    background: url(../assets/tombrady1.jpg) no-repeat center center fixed !important;

    -webkit-background-size: cover;
    background-size: cover;
    display: block !important;
}

As I mentioned above I have tried using CSS classname:active. I have also tried multiple java script solutions and they simply do not change the background url to image1 to image2.

Upvotes: 7

Views: 187

Answers (1)

Brian John
Brian John

Reputation: 599

My recommended solution is to create a CSS class for both the initial state of the element (example .tasteTheRainbow) as well as the new state (example .tasteTheRainbowNew), and then use Javascript to apply/remove the class.

$(function () { 
    $(".gA3").click(function () {
         $(this).parent(".tasteTheRainbow").toggleClass("tasteTheRainbowNew"); 
    }); 
});

See my JSfiddle here: http://jsfiddle.net/oxv0rc1k/2/

Also, note that I loaded in JQuery because my JS sucks without it.

Upvotes: 7

Related Questions