Abdullah Medhat
Abdullah Medhat

Reputation: 21

how to change background to button selected?

in that menu how to change background for selected button? this is code for menu

<ul id="menu">
      <li class="current_page_item"><a class="button" id="showdiv1"><span>Homepage</span></a></li>
      <li class="current_page_item1"><a class="button" id="showdiv2"><span>Experience</span></a></li>
      <li class="current_page_item2"><a class="button" id="showdiv3" ><span>Vision</span></a></li>
      <li class="current_page_item3"><a class="button" id="showdiv4" ><span>Portfolio</span></a></li>
      <li class="current_page_item4"><a class="button" id="showdiv5"><span>Social</span></li>
      <li class="current_page_item5"><a class="button" id="showdiv6"><span>About me</span></a></li>
</ul>

Upvotes: 0

Views: 132

Answers (2)

Kourosh Raoufi
Kourosh Raoufi

Reputation: 1652

first give a specific class to all target elements (here we assign class1)

    <style>
    .selected{
        background-color:green;
    }
</style>
    <ul id="menu">
          <li class="class1 current_page_item"><a class="button" id="showdiv1"><span>Homepage</span></a></li>
          <li class="class1 current_page_item1"><a class="button" id="showdiv2"><span>Experience</span></a></li>
          <li class="class1 current_page_item2"><a class="button" id="showdiv3" ><span>Vision</span></a></li>
          <li class="class1 current_page_item3"><a class="button" id="showdiv4" ><span>Portfolio</span></a></li>
          <li class="class1 current_page_item4"><a class="button" id="showdiv5"><span>Social</span></li>
          <li class="class1 current_page_item5"><a class="button" id="showdiv6"><span>About me</span></a></li>
    </ul>

then you can access remotely to specific item with their class name

important notice: you have to use javascript code after html

var element = document.getElementByTagName('class1'),i,j;
for(i in element){
    element[i].onclick = function() {

        this.className = this.className + ' selected';

        for(j in element){
            element[j].className = str.replace(" selected", "");
        }
    }
}

my suggestion: there is a lots of javascript framework they can help you

for using javascript faster and easier one of them is Jquery

with jquery you can do it with less time and less code

this code with Jquery:

$(document).ready(function() {
    $('#menu li').click(function() {

        $('#menu li').removeClass('.selected');

        $(this).addClass('.selected');

    });
});

Upvotes: 2

Soheil Shiri
Soheil Shiri

Reputation: 11

You can use document.body.style.backgroundColor = "red"; for changing the bachground color.
you must define onclick :

<button onclick="myFunction()">Click me</button>

and in JS file :

function myFunction() { 
  document.body.style.backgroundColor = "red"
}

Upvotes: 0

Related Questions