Reputation: 503
I'm trying to learn how to use JQuery and I'm running into problems. Triggering one function is setting off the effects of other unrelated functions and I don't know why. When I click the box2 element why do the effects of box1 fire as well?
When a "p" element is clicked, box1 should expand to 100% width. When "box2" is clicked it should expand to 400px height. The problem is that when I click box2 , box1 is also changing.
NOTE: this is only an exercise, so no need to worry about doing things perfectly here. Just trying to figure out this quirk. Thanks!
<html>
<head>
<style>
*{ padding:0px; margin:0px;}
p { font-family:Verdana, Geneva, sans-serif; font-size:40px; font-weight:bold; color:#fff;}
#box1 { background-color:#003366; height:60px; width:350px; padding:15px;}
#box2 { background-color:red; height:60px; width:350px; padding:15px;}
.center{text-align:center;}
.red{color:red;}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function()
{
<!-----------------function p onclick--------------->
$("p").click(function()
{
$("#box1").animate({ width: '100%'});
$("h1,h2,p").addClass("center");
});
<!-----------------function box2 onclick--------------->
$("#box2").click(function()
{
$("#box2").animate({ height: '400px'});
});
});<!--end document.ready JQUERY-->
</script>
</head>
<body>
<div id="box1"><p>Test It</p></div>
<h1>Just some words here.</h1>
<div id="box2"><p>Test It</p></div>
</body>
</html>
Upvotes: 0
Views: 55
Reputation: 43087
Your box1
click handler is updating all h1
, h2
, and p
elements. Add some context if you only want children of box1
.
$("h1,h2,p", "#box1").addClass("center");
Also, as others have mentioned, your first click handler is assigned to all p
elements.
Upvotes: 1
Reputation: 382167
You don't click just box2
, you click the paragraph p
which is inside box2
, that's why it triggers also the first handler.
You could change
$("p").click(function()
to
$("p").not('#box2 p').click(function()
to avoid this problem.
Upvotes: 1
Reputation: 1614
You have a click handler assigned to all paragraphs, and there's a paragraph in both boxes:
$("p").click(function()
Change that to:
$("#box1").click(function()
or
$("#box1").find('p').click(function()
Upvotes: 2