Change background to an element via jquery

Asked

Viewed 591 times

-1

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

This doesn’t happen only once, it can happen several times and I never know which element I’m clicking on because they have the same class.

inserir a descrição da imagem aqui

  • 2

    Please post the code you have already tried instead of image.

2 answers

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>

<div class="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>

1


You can do that with jQuery:

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

So every time an element a direct descendant of a li clicked click happens two things:

  • the event click is canceled to avoid changing page (you can also avoid this with href="#"
  • the element clicked (the this inside that callback) receives a new background color.

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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.