How do I change the font family of a paragraph when it is clicked? Im using jQuery

so, I’ve been trying to make a jQuery function that would change the font style of a paragraph once it is clicked.

Here is the code I’ve tried:

$(document).ready(function() {
  $("#story-p").click(function() {
    $(this).css({
      "font-family": "Arial, Helvetica, sans-serif",
      "font-size": "200%",
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <img class="background" src="restaurant.jpg" style="display: none" />
  <h1 class="heading">Fuego</h1>
  <div class="container">
    <h1 class="story">Our Story</h1>
    <p class="story-p">
      Test
    </p>
</body>

I can’t figure out why it wouldn’t work?

Am I missing something?

Many thanks

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Its not working because you selector to attach the click event uses $('#story-p') which means its targeting an element with id=story-p but your paragraph does not have an id instead it has the class as story-p.

So change your selector like below and it will start working.

$(document).ready(function() {
  $(".story-p").click(function() {
    $(this).css({
      "font-family": "Arial, Helvetica, sans-serif",
      "font-size": "200%",
    });
  });
});
<body>
  <img class="background" src="restaurant.jpg" style="display: none" />
  <h1 class="heading">Fuego</h1>
  <div class="container">
    <h1 class="story">Our Story</h1>
    <p class="story-p">
      We are an Asian inspired streetfood restaurant located in the Cape Town CBD. We pool together recipes from Vietnam, Thailand and Japan and create an authentic Asian food experience here in South Africa. Our owners, have spent years working in restaurants
      all over Asia and have collaborated to create a collection of their favourite and most popular dishes. We have been open now for 2 years and plan to continue this journey well into the future. Come and visit us!
    </p>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Method 2

// first of all with modern javascript you don’t really need to use jquery. And you used the wrong selector for your paragraph elemnet.

<script>
    $(document).ready(function(){
        $(".story-p").click(function(){
        $(this).css("font-family", "Arial, Helvetica, sans-serif");});
    });
</script>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x