Shakeel Ahmad
Shakeel Ahmad

Reputation: 13

How can I shorten this jquery code

I am trying to learn jquery from online tutorials. Following code is working for me but how can I shorten and improve this code? this can be viewed on bottom of this page

$(document).ready(function() {
    $("#alltiles > div").mouseenter(function() {
        $(this).addClass("tile1");
        $(this).removeClass("tile");
        $('img', this).addClass("tileimg1");
        $('img', this).removeClass("tileimg");
        $('p', this).addClass("tilep1");
        $('p', this).removeClass("tilep");
    });
    $("#alltiles > div").mouseleave(function() {
        $(this).addClass("tile");
        $(this).removeClass("tile1");
        $('img', this).addClass("tileimg");
        $('img', this).removeClass("tileimg1");
        $('p', this).addClass("tilep");
        $('p', this).removeClass("tilep1");
    });
});

Upvotes: 1

Views: 47

Answers (2)

svichkar
svichkar

Reputation: 1856

You can do this by using CSS styles only :) Here are a lot of action which can be declared in This is the shortest solution.

Upvotes: 0

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You could use toggleClass() on hover :

$(function() {
    $("#alltiles > div").hover(function() {
        $(this).toggleClass("tile","tile1");
        $('img', this).toggleClass("tileimg","tileimg1");
        $('p', this).toggleClass("tilep","tilep1");
    });
});

Upvotes: 4

Related Questions