Jason
Jason

Reputation: 2298

jQuery toggling element position

Trying to have jQuery toggle the position of a certain element so that I can hide and show it via a click event. I start out with my class having a property of position: absolute and left: 9000em (to keep it way off screen). Then I want to add another class with the property of left: 0 to bring the element back on screen. It is not working. Using jQuery 1.11.3. Here is my HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/normalize.css">
    <link href='http://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>
    <script src="js/jquery-1.11.3.min.js"></script>
    <script src="js/script.js"></script>
</head>

<body>

   <section>

       <button id="toggle">Hello there</button>

       <div class="background">

       </div> 

   </section>

</body>

</html>

my CSS

.active {
    left: 0; 
}

.background {
    position: absolute;
    left: 9000em;
    background-color: lightgray;
    width: 500px;
    height: 100px;
}

and my jQuery

$("document").ready(function() {

     $("#toggle").on("click", function(evt) {

        $(".background").toggleClass("active");

      });

});

Upvotes: 0

Views: 748

Answers (3)

Waqar
Waqar

Reputation: 848

.active
{
    left:0 !important
}

prioritize your left:0 with !important.

DEMO: https://jsfiddle.net/735mmLqf/

Upvotes: 0

gmast
gmast

Reputation: 192

If you write your .background style AFTER .active style it will overwrite the "left" directive. You could write the .active style in your css after your .background class.

.background {
    position: absolute;
    left: 9000em;
}
.active {
    left: 0; 
}

Upvotes: 1

Platte Gruber
Platte Gruber

Reputation: 3193

Your jQuery is fine, just alter your css to be more selective:

.background.active {
    left: 0; 
}

And your working fiddle: http://jsfiddle.net/u9a26crc/

Upvotes: 1

Related Questions