Change background to an element using jquery

-1

I would like to do something like this represented in the image below or I wanted to change the background of <a href> when it is clicked on another <a href> below.

This does not happen once, it can happen several times and I never know which element I am clicking on because they have the same class .

    
asked by anonymous 27.06.2016 / 13:54

2 answers

1

You can do this with jQuery:

$('li > a').on('click', function(e) {
    e.preventDefault();
    this.style.backgroundColor = '#fdf';
});

So every time a a pendent element of a li is clicked two things happen:

  • event click is canceled to avoid changing page (you can also avoid this with href="#"
  • The clicked element ( this within this callback) gets a new background.

Example:

$('li > a').on('click', function(e) {
    e.preventDefault();
    this.style.backgroundColor = '#fdf';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li>texto</li>
    <li>texto</li>
    <li><a href>Link</a>
        <ul>
            <li>texto</li>
            <li>texto</li>
            <li><a href>Link</a>
                <ul></ul>
            </li>
        </ul>
    </li>
</ul>
    
27.06.2016 / 14:22
1

$(document).ready(function(){                        // Espera para executar ate o dom ter sido renderizado
  $('.change_color').on('click', 'li', function(){   // Cria um evento de click para os li do elemento ul
    var color = this.getAttribute('data-value');     // recupera a cor que esta no data-value
    $('.content').css({background:color});           // aplica a cor no elemento do class content
  })
})
.content{
  width:100px;
  height:50px;
  background:yellow;
}

.change_color li {
    cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="content">
</div>

<ul class="change_color">
  <li data-value="red">red</li>
  <li data-value="green">green</li>
  <li data-value="blue">blue</li>
  <li data-value="#CCC">gray</li>
</ul>
    
27.06.2016 / 14:04