Erik Blomqvist
Erik Blomqvist

Reputation: 481

How can I shorten this jQuery code?

Sorry for the non-saying title, but I have a question on how to shorten a piece of jQuery code:

$(function() {
    $("#profile1").click(function() {
        $("#profile1").addClass("focused");
        $("#profile2").removeClass("focused");
        $("#profile3").removeClass("focused");
    });
    $("#profile2").click(function() {
        $("#profile1").removeClass("focused");
        $("#profile2").addClass("focused");
        $("#profile3").removeClass("focused");
    });
    $("#profile3").click(function() {
        $("#profile1").removeClass("focused");
        $("#profile2").removeClass("focused");
        $("#profile3").addClass("focused");
    });
});

For what I can see, a toggleClass wouldn't do it, since I can press that object two times in a row and therefore make multiple objects being focused at the same time, while I'm looking for some kind of a switch, where only one object can be in focus (i.e. have the class 'focused') at a time.

This is me being kind of a beginner, but I'm guessing I should involve 'this' somewhere, but I can't figure out how.

Thanks in advance! You guys rock!

Upvotes: 1

Views: 75

Answers (1)

Bergi
Bergi

Reputation: 664297

Remove the class from all of them, then add it to the targeted one only. Also, use a single event handler only and reference the event target dynamically.

$(function() {
    var $profiles = $("#profile1, #profile2, #profile3");
    $profiles.click(function(e) {
        $profiles.removeClass("focused");
        $(this).addClass("focused"); // or use `e.target` instead of `this`
    });
});

You might also use a class .profile instead of ids to select the elements now.

Upvotes: 7

Related Questions