skip to Main Content

Index.html

<html>
<head>
<script
      src="https://code.jquery.com/jquery-3.4.1.js"
      integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
      crossorigin="anonymous"></script>
<!-- jquery-3.4.1.min -->
<script type="text/javascript" src="custom.js"></script>
</head>
<body>
<div class="epic" style="color:red">hello this is title</div>
<div>hello this is title</div>
<input type="button" placeholder="click it" value="click">
</body>
</html>

custom.js

$( document ).ready(function($){       
   $(":button").click(function(){    
    $(".epic").attr("style","font-size:100px");    
   });        
});

Now What I want Is when I click the button than I should be able to give the font-size that I want but keep the previous color red also .
The code that I have written makes the font 100 but color is gone ,so Is there any way to keep the color and still be able to modify the font.

3

Answers


  1. You can use .css() to set the particular style property (font-size):

    $( document ).ready(function(){
      $(":button").click(function(){
        $(".epic").css("font-size", "100px");
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="epic" style="color:red">hello this is title</div>
    <div>hello this is title</div>
    <input type="button" placeholder="click it" value="click">
    Login or Signup to reply.
  2. Use .css method instead. And pass a object of CSS properties. When you will call it again, it will just add the new properties to existing one.

    In your solution, you are overwriting the complete style attribute everytime. So it is removing the older properties.

    $(document).ready(function() {
    
      $(":button").click(function() {
        $(".epic").css({
          "font-size": "50px",
          "background-color": "blue"
        });
        $(".epic").css({
          "color":"white"
        });
      });
    
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="epic" style="color:red">title</div>
    <div>hello this is title</div>
    <input type="button" placeholder="click it" value="click">
    Login or Signup to reply.
  3. You could use the jQuery addClass() method to keep the original CSS class and add a new one:

    $("button").click(function(){
      $(".epic").addClass("clicked");
    });
    

    And in the CSS:

    .clicked {
        font-size: 50px;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search