Sino
Sino

Reputation: 990

Javascript change color on click and keep the same color

I have currently the following code:

<li><a href="index.php" id="1" onclick="document.getElementById('1').style.background = '#8B4513';">Weblog</a></li>

This changes the color, but because it opens index.php the color won't stay at the same color. It returns to the original color.

How can i keep it the same color, in a different page?

Thanks

Upvotes: 0

Views: 2126

Answers (3)

OptimusCrime
OptimusCrime

Reputation: 14863

Javascript is clientside, which means that any changes done happens in a way on the user's screen.

PHP is serverside. You send a request to the server, it processes the request and displays the output.

If you want to highlight the current webpage, this is not the way to do it.

I'd suggest you add a line of PHP on each file in the li a-list. For example:

<?php if ($URL == 'index.php') echo 'class="selected"'; ?>

And using CSS to make the link with the class selected red ones.

Upvotes: 1

Gais
Gais

Reputation: 575

From the code provided it looks like you are trying to style an element once a user has clicked a link.

Javascript seems unnecessary here. I would just use the :visited css pseudo-class to style the element.

For example;

a:visited { text-decoration: line-through; }

Upvotes: 1

Niels
Niels

Reputation: 49919

To start, an ID can not start with a number.

You have to catch the selected page on the server side and give it a class like selected and use CSS to do something like:

li.selected a
{
    background: #8B4513;
}

If you have no clue how to set a selected page with PHP, read this article: http://darkstar-media.blogspot.com/2009/04/css-page-selected-with-php.html

Upvotes: 0

Related Questions