Grow your CSS skills. Land your dream job.

jQuery Shorthand

  • # November 19, 2010 at 1:27 pm

    So I was working on a little snippet of jQuery, so please pardon my rudimentary skills, but I was wondering is there a way to make the following code shorter?

    Basically this “little” bit of code hides/shows a div with an image and some text by adding and removing certain classes when a certain item is hovered over in a list -it also highlights the list link on hover. I was just thinking that perhaps I could condense it a bit more?

    Thanks,
    Lindsey :D

    # November 20, 2010 at 1:04 pm

    if there is, I don’t see it

    # November 20, 2010 at 6:00 pm

    I took a crack at it. I can’t test anything of course, so I can’t 100% vouch for it, but this should get you going at much more flexible and DRY code:

    // DOM Ready
    $(function() {

    // Give #nav-fragment-1 through 4 a class name of "nav-fragment"
    // Gove #fragment-1 through 4 a class name of "fragment"

    var $navFragments = $(".nav-fragment"),
    $fragments = $(".fragment");

    // MOUSEENTER
    $navFragments.hover(function() {

    // Get "fragment-2" from "nav-fragment-2"
    var relatedID = "#" + this.id.substring(4),
    // Make into jQuery object
    relatedEl = $(relatedID);

    // Remove hiding class name from related fragment
    releatedEl.removeClass("ui-tabs-hide");

    // Add hiding class name to all other fragments
    $fragments.not(relatedEl).addClass("ui-tabs-hide");

    // Remove selected class from all other nav-fragments
    $navFragments.removeClass('ui-tabs-selected');

    // Add selected class to hovered nav-fragment
    $(this).addClass('ui-tabs-selected');

    // MOUSELEAVE
    }, function() {

    // Seems like you wouldn't need to do anything here...

    });

    });
    # November 22, 2010 at 5:02 pm

    Oh, thanks Chris! I’m going to try that out and see how it goes, thanks!

    -Lindsey

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".