New to jquery , trying to show/hide a div onclick, please advise?
I am having a hard time trying to show/hide a div
on click. Basically you click on the flowers (div
, the one I want to toggle) and they fade out or hide (which is good) and then disappear (which is not good). I need to be able to click on the flowers and have them fade out and then be able to click (on the same "flowers" div
) and have them fade back in or show (like a light switch).
Here's the JavaScript code I'm using:
$('.show_hide').click(function() {
$("#treeFlowers").fadeToggle()
return false;
});;
});
And here's the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>App 1-1</title>
<link rel="stylesheet" type="text/css" href="css/master.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript" src="js/master.js"></script>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/tr开发者_运维百科unk/html5.js"></script>
<![endif]-->
</head>
<body>
<div id="mainWrapper">
<div id="treeFlowers">
<a href="#" class="show_hide"><img src="images/app1-1/treeFlowers.png" alt="tree Flowers"/></a>
</div>
<div id="treeApp">
<img src="images/app1-1/tree.png" alt="light tree"/>
</div>
<div id="textApp">
<img src="images/app1-1/text1.png" alt="text"/>
</div>
<div id="flowers">
<img src="images/app1-1/flowers.png" alt="flowers" />
</div>
</div>
</body>
fadeToggle()
is an alias of fadeIn()
and fadeOut()
, which set display:none;
after the opacity is brought down and display:block;
, before opacity is brought back up. What you'll want to do is wrap your image and set the click event on the wrapper. For example:
<div class="flower">
<img src="my_flower.jpg" />
</div>
JQuery:
$('.flower').click(function(){
$(this).children('img').fadeToggle();
});
You should nest the flowers div inside another container div which will be the one being clicked on, lets call it flower-container, then do a toggle on it as follows:
$(function(){
$('#flowers-container').toggle(
function(e){ $('#threeFlowers').hide(); },
function(e){ $('#threeFlowers').show(); });
});
Have you tried
<script>
$('.show_hide').click(function(){
$("#treeFlowers").toggle();
});
</script>
Putting at the end of your document, just before the </body>
tag ?
Also, the element with show_hide class should not be nested inside the div with treeFlowers id.
精彩评论