Style background image with JS not working

13,170

Solution 1

I think you wanted to target the a element inside the div.pagar. You can do something like this:

HTML

<div class="pagar" ><a href="#" id="pagar" onclick="clickado()"></a></div>

Javascript

function clickado() {
    document.getElementById('pagar').style.backgroundImage = 'url("imagens/pagar-clickado.jpg")';
}

Solution 2

You can try add new style class for the event click:

 .pagar.click a:hover {
 background-image: url('imagens/pagar-clickado.jpg');
 background-repeat: no-repeat;
 }

And change the function javascript:

    function clickado() {
    document.getElementById('pagar').classList.add('click');
}

With the new api for working with classes, it is more easier

Solution 3

You could write a much better solution attaching a class with your javascript to the '.pagar' element, for example "clicked". Then you could add a couple of lines to your CSS:

.pagar.clicked a,
.pagar.clicked a:hover {
    background-image: url('imagens/pagar-clickado.jpg');
}

This is the javascript of course:

<script>
function clickado() {
document.getElementsByClassName('pagar')[0].className += 'clicked';
}
</script>

I learned that, to keep code simple and mantainable, moving style definition to CSS (removing it from javascript) is usually the best practice to follow.

Share:
13,170
GtOkAi
Author by

GtOkAi

Updated on August 10, 2022

Comments

  • GtOkAi
    GtOkAi almost 2 years

    Ok, maybe its a stupid question with a little bug, but I'm trying fix this and I can not:

        <style>
     .pagar a {   
     width:  200px;
     height: 85px;
     display: block; 
     background-image: url('imagens/pagar.jpg'); 
     background-repeat: no-repeat;
    
         } 
    .pagar a:hover { 
     background-image: url('imagens/pagar-hover.jpg');
     background-repeat: no-repeat; } 
    </style>
    
        <script>
        function clickado() {
        document.getElementsByClassName('pagar')[0].style.backgroundImage = 'url("imagens/pagar-clickado.jpg")';
        }
        </script>
    

    HTML:

    <div class="pagar" id="pagar" ><a href="#" onclick="clickado()"></a></div>
    

    The problem:

    The .style.backgroundImage just does not change to "imagens/pagar-clickado.jpg", the the path is correct, I do not get error in console and ('pagar')[0] is also correct too.

  • GtOkAi
    GtOkAi over 9 years
    Exactly! Something so simple, but even passing the code a thousand times, go unnoticed.
  • A1rPun
    A1rPun over 9 years
    When you click the a multiple times you end up with the div (not even the a element) having its className like 'clickedclickedclicked'. And he has already an image for hover.