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!
Here’s my code
<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>
You have a click handler assigned to all paragraphs, and there’s a paragraph in both boxes:
Change that to:
or