Bradley Roberts
Bradley Roberts

Reputation: 119

Javascript change class onclick

Im just trying to get to grips with javascript / ajax / jQuery so Im building a ticket system for my website.

Anyway, I have a table at the top of the page;

    <table align="center" class="thinline" width="600" border="1" cellpadding="2" bordercolor="black">
    <tr class="subtopic" style="font-size: 15px;">
        <td><a onClick="javascript: ShowNewTickets()">New Tickets</a></td>
        <td><a onClick="javascript: ShowYourTickets()">Your Tickets</a></td>
        <td><a onClick="javascript: ShowPuplicTickets()">Public Tickets</a></td>
    </tr>
</table>

When the page loads I want "New Tickets" to have the class "selected". If they hover the mouse over any of the unselected menus then it has a highlighted effect. Once they click onto another link the "selected" class will be removed from the other TD and added to the new TD.

I have tryed onmouseover and onmouseout to do the highlight effect but it messes up when it comes to the link which is already highlighted.

I have also tryed,

    $('.off').live('mouseenter', function() {
    if ($(this).hasClass('selected') == false) {
        $(this).removeClass('off').addClass('highlighted');
    }
});

But that then keeps the TD highlighted.

Thanks for reading.

Upvotes: 0

Views: 1638

Answers (3)

Bram
Bram

Reputation: 1112

As Sergio Tulentsev mentioned, you should use the :hover pseudo class to handle the highlight effect. To handle the "selected" class, you could do something like this:

$('.subtopic').on('click', 'a', function(e) {
    $('.subtopic a').removeClass('selected'); // remove the class from all the links
    $(this).addClass('selected'); // add it to the clicked link
}

Note that I am using the new jquery function .on() instead of .click, .live or .delegate. The way .on() works, you will make sure you only bind events to the links in the .subtopic row. Using .on() also guarantees your events will still fire when adding new links dynamically to the DOM.

Upvotes: 2

CBusBus
CBusBus

Reputation: 2359

Check out.toggleClass(), it does what the name suggests.

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230326

You should use :hover pseudo-class.

It will handle mouse over/out for you.

Upvotes: 2

Related Questions