-3

The following is what my HTML document looks like:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="scripts/homepage-script.js"></script>
</head>

<body>
<div id="how-it-works">
    <p>How It Works</p>
    <img src="some-imageurl">
    <div id="steps">
    <p>Step 1</p>
    <p>Step 2</p>
    <p>Step 3</p>
</div>

And here is my script:

$('#steps > p').on('click' , function(){
    $('steps > p').css('background', 'yellow');
});​

Why is my script not running on my website?

ajf1000
  • 409
  • 5
  • 13

3 Answers3

1

You need to wrap the jQuery in a document ready and you can use $(this) since it is targetted in the onclick event:

$(document).ready(function(){
     $('#steps > p').on('click',function(){
          $(this).css('background', 'yellow');
    });​
})

however what I would recommend is having a highlight class that is then toggled in the onclick event;

//CSS
.highlight{background:yellow}


$(document).ready(function(){
     $('#steps > p').on('click',function(){
          $(this).toggleClass('highlight');
    });​
})

Tht way you are adding / removing a class instead of altering the elements CSS.

If you want to add the highlight class to all the p's in that div as per @Phil comment -

$(document).ready(function(){
     $('#steps > p').on('click',function(){
         $('#steps > p').toggleClass('highlight');
    });​
})

$(document).ready(function(){
     $('#steps > p').on('click',function(){
          $(this).toggleClass('highlight');
    });
})
.highlight{background:yellow}
<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="scripts/homepage-script.js"></script>
</head>

<body>
<div id="how-it-works">
    <p>How It Works</p>
    <img src="some-imageurl">
    <div id="steps">
    <p>Step 1</p>
    <p>Step 2</p>
    <p>Step 3</p>
</div>
  </body>
  </html>
gavgrif
  • 15,194
  • 2
  • 25
  • 27
0

You are missing the # selector in your nested line of code:

$('#steps > p').css('background', 'yellow');

This will make all of the p elements turn to a yellow background. If you only want the element the user clicked, then reference the "selected" object with $(this):

$('#steps > p').on('click' , function(){
    $(this).css('background', 'yellow');
});
Singular1ty
  • 2,577
  • 1
  • 24
  • 39
0

The script should be after the div.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

</head>

<body>
<div id="how-it-works">
    <p>How It Works</p>
    <img src="some-imageurl">
    <div id="steps">
    <p>Step 1</p>
    <p>Step 2</p>
    <p>Step 3</p>
</div>

<!--The script should be after the div.-->
<script src="scripts/homepage-script.js"></script>
Phil
  • 157,677
  • 23
  • 242
  • 245