stackover
stackover

Reputation: 6935

alter css of selected anchor tag with jquery

i have pagination links like 1,2,3,4...am trying to change appearance of current page using something like this

$(".pg"+this.currentPage).css({"color":"#2F557B",
                           "background-color":"#FFFFC4",
                          "border":"solid 1px #2F557B",
                           "cursor":"default"});

eg. when <a> #1 is selected the above applies. but <a> #2 is selected this also have above style (as I want) but how can i reset <a> #1 style to older one? Any idea would be highly appreciated.

Upvotes: 0

Views: 8415

Answers (4)

dalbir
dalbir

Reputation: 11

where to keep this function in the css or the page where div is created

$('#PageLinks a').click( function(e) {
    //Remove the selected class from all of the links
    $('#PageLinks a.selected').removeClass('selected');

    //Add the selected class to the current link
    $(this).addClass('selected');
});

Upvotes: 1

MarkXA
MarkXA

Reputation: 4384

Find a selector that applies to all the links (e.g. ".pager" or "#pager a"). Also create a CSS class that applies your extra styles (say ".selected"). Then do

$(".pager").removeClass("selected");
$(".pg" + this.currentPage).addClass("selected");

This will clear the "selected" style from all your links and reapply it to only the one you need.

Upvotes: 1

Mark Biek
Mark Biek

Reputation: 150819

The easiest thing is to define your selected-state CSS as a class.

When you set the selected state of the current link, you remove that CSS class from all other links first.

For example:

Let's pretend your markup looks something like this. You have your pagination links in a div and the Page 1 link is currently selected.

<style type="text/css">
    .selected {
        color:  #2F557B;
        background:  #FFFFC4;
        border:  1px solid #2F557B;
        cursor:  default;
    }
</style>

<div id="PageLinks">
    <a href="#1" class="selected">Page 1</a>
    <a href="#2">Page 2</a>
    <a href="#3">Page 3</a>
</div>

Let's also pretend that we're going to change the style of the link on click.

$('#PageLinks a').click( function(e) {
    //Remove the selected class from all of the links
    $('#PageLinks a.selected').removeClass('selected');

    //Add the selected class to the current link
    $(this).addClass('selected');
});

Upvotes: 4

tcnolan
tcnolan

Reputation: 498

You might want to create a class that has additional CSS properties on it and use .toggle() to add/remove the class as needed.

http://api.jquery.com/toggle/

Upvotes: 0

Related Questions