JavaScript Code


jQuery – Fade to specific opacity



Fade HTML Element(s) to specific opacity using jQuery

Selected some HTML elements in the document, fade them to specific opacity using jQuery.

Solution

To fade selected HTML elements to specific opacity using jQuery, call fadeTo() function on the selected elements.

For example, the syntax to fade paragraphs to an opacity of 0.4 in 1000 milliseconds is

$("p").fadeTo(1000, 0.4);

Programs

1. Fade all paragraphs to 0.4 opacity in 1000 milliseconds.

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script>
      function myAction() {
        $("p").fadeTo(1000, 0.4);
      }
    </script>
  </head>
  <body>
    <button onclick="myAction()">Fade paragraphs to 0.4 opacity</button>
    <p>This is a paragraph.</p>
    <p>This is another paragraph.</p>
  </body>
</html>

2. Fade all link elements to 0.2 opacity in 500 milliseconds.

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script>
      function myAction() {
        $("a").fadeTo(500, 0.2);
      }
    </script>
  </head>
  <body>
    <button onclick="myAction()">Fade links to 0.2 opacity</button>
    <p>Welcome to <a href="#jquery">jQuery</a></p>
    <p>Welcome to <a href="#jquery">jQuery 3</a></p>
  </body>
</html>


copyright @2023