Xavier
Xavier

Reputation: 87

How to override previous onClick css class change (jQuery)

I wrote this code which animates (makes appear/disappear) a few elements on my page, including my 'work' div. It's triggered when clicking the link with class .fade

But I want that the others links of my menu, when clicked, override previous animation by making 'work' div fade away, then I can bring on & animate 'contact' div the way I did for the work div.

HTML part

    <div id="main">
    <h1>Hello</h1>
    <h2>This is a second heading/h2>

    <ul>
        <li><a href="#" class="fade">one</a></li>
        <li><a href="#" class="fade">two</a></li>
        <li><a href="#" class="fade">three</a></li>
    </ul>

    </div>

<div id="work">
</div>

<div id="contact">
</div>

jQuery part

$(function(){
  $(".fade").click(function(){
     $('#main').animate({ opacity: 1, top: "12%" }, 800);   
     $('h1, h2').animate({ opacity: 0.5 }, 800);     
     document.getElementById('work').style.cssText = "display: block";
     $('#work').animate({ opacity: 0 }, 0);
     $('#work').animate({ opacity: 1, top: "350px" }, 800);
  });
});

Upvotes: 0

Views: 1101

Answers (1)

Barmar
Barmar

Reputation: 781741

Add an attribute to each link saying which DIV it should animate, and add a class to all the target DIVs:

<ul>
    <li><a href="#" class="fade" data-target="work">one</a></li>
    <li><a href="#" class="fade" data-target="contact">two</a></li>
    <li><a href="#" class="fade" data-target="something">three</a></li>
</ul>

</div>

<div id="work" class="target">
</div>

<div id="contact" class="target">
</div>

In your jQuery, use that data as the DIV instead of hard-coding #work.

$(function(){
  $(".fade").click(function(){
     $('#main').animate({ opacity: 1, top: "12%" }, 800);   
     $('h1, h2').animate({ opacity: 0.5 }, 800);
     var target = "#" + $(this).data("target");
     $(".target:not("+target+")").hide();
     $(target).show();
     $(target).animate({ opacity: 0 }, 0);
     $(target).animate({ opacity: 1, top: "350px" }, 800);
  });
});

It looks like you're implementing tabbed browsing, maybe look at the jQuery UI Tab widget?

Upvotes: 1

Related Questions