Reputation: 248
I am trying to show/hide div when click on an image. when I click on the image nothing happens. What is wrong with my code
<script type="text/javascript">
$('#close').click(function(){
$('#main').show();
$('#login').hide();
});
</script>
<div style="float:right;"><a href="#">Close <img id="close" src="assets/close.png"></a></div>
Upvotes: 0
Views: 19195
Reputation: 107
jQuery live is deprecated, jQuery documentation indicates to use .on("click", function(){
});
Upvotes: 0
Reputation: 537
<script type="text/javascript">
$(function(){
$('#close').live('click',function(){
$('#main').show();
$('#login').hide();
});
});
</script>
<div style="float:right;"><a id="close">Close <img src="assets/close.png" /></a></div>
Use the live function. Also, I would target the a tag so the text also triggers it.
Upvotes: 1
Reputation: 1107
When it comes to using id vs class names there is a pretty good rule of thumb. If you are going to use it more than once in a template make it a class. In the case of main,login,header or footer an Id works fine but here I would use a class.
Now that is not what's causing your issue but I thought I would point that out. Your problem is probably because the selector is trying to find something that is not there yet. You have 2 choices
1.) Move your script to bottom of the page
2.) Wrap your code in a ready function (only executes once the dom is ready.
Here is an updated code example with my suggestions
<!DOCTYPE HTML>
<html>
<head>
<title>Click Handler</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('.close').click(function(){
$('#main').show();
$('#login').hide();
});
})
</script>
</head>
<body>
<div style="float:right;"><a href="#" class="close">Close <img src="assets/close.png" class="close"></a></div>
<div id="main" style="display:none;">Main</div>
<div id="login">Login</div>
</body>
</html>
Upvotes: 0
Reputation: 13922
It's probably because when your script executes, the close
image doesn't exist yet. Wrap your setup in a $(document).ready
block
Slight update:
In a quick test on my own machine, calling .click(..)
on the image tag didn't do anything. I changed it so the close
element is actually the <a>
, and things worked.
Relevant HTML:
<a id="close" href="#">Close (image goes here)</a>
Upvotes: 2
Reputation: 2821
First of all you shouldn't have the same ID multiple times.
Then:
<script type="text/javascript">
$('#image').click(function(){
$('#close').toggle();
});
</script>
<div id="close" style="float:right;"><a href="#">Close <img id="image" src="assets/close.png"></a></div>
Of course this will hide your image also so you don't have anything to click on.. but it's a start.
Upvotes: 0