User
User

Reputation: 13

check if class in element equals a value javascript

I have a menu and my users should be able to resize it by pressing a button. I have the following code:

<header class='large'>
    <nav>
        <ul>
            <li><a href="#">Link 1</a></li>
            <li><a href="#">Link 2</a></li>
            <li><a href="#">Link 3</a></li>
        </ul>
    </nav>
</header>
<button onclick="resizeMenu()">Resize</button>




function resizeMenu()
    {
        if(exists(header.large) {
            $("header").removeClass("large").addClass("small");
        } elseif(exists(header.small)
            $("header").removeClass("small").addClass("large");
        }
    }

I don't really have an idea on how I should write the condition. By the way I am using jquery.

Upvotes: 1

Views: 6908

Answers (4)

Sudharsan S
Sudharsan S

Reputation: 15393

Simply Write. Use Toggle Class in Jquery for add and remove Class

function resizeMenu()
{

   $("header").toggleClass("large small");

}

Upvotes: 0

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

is this you want?

<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
    $(document).ready(function () {
        $("#resize").click(function () {
            $("nav").animate({
                height: ["toggle", "swing"]
            }, {
                duration: 500,
                complete: function () {

                }
            });

        });
    });

</script>
</head>
<body>
<header>
<nav>
    <ul>
        <li><a href="#">Link 1</a></li>
        <li><a href="#">Link 2</a></li>
        <li><a href="#">Link 3</a></li>
    </ul>
</nav>
</header>
<button id="resize">
    Resize</button>
</body>
</html>

Upvotes: 0

Zzyrk
Zzyrk

Reputation: 905

You can use the .hasClass from jQuery:

function resizeMenu()
{
    if($("header").hasClass("large")) {
        $("header").removeClass("large").addClass("small");
    } elseif($("header").hasClass("small")) 
        $("header").removeClass("small").addClass("large");
    }
}

Upvotes: 3

Arun P Johny
Arun P Johny

Reputation: 388316

Use toggleClass() to switch between the 2 classes

function resizeMenu() {
    $("header").toggleClass("large small");
}

To check whether an element has class use .hasClass()

function resizeMenu() {
    var $header = $('header')
    if ($header.hasClass('large')) {
        $header.removeClass("large").addClass("small");
    } else if ($header.hasClass('small')) {
        $header.removeClass("small").addClass("large");
    }
}

Upvotes: 2

Related Questions