CodersTechZone
  • .NET
    • C#
    • ASP.Net
  • HTML
  • Javascript
  • CSS
  • Database
    • SQL Server
    • MYSql
    • Oracle
  • AI
  • TechNews
  • Web-Stories

How to Call JavaScript Function in HTML Without Onclick?

Shawpnendu Bikash Maloroy

July 10, 2024
How to Call JavaScript Function in HTML Without Onclick?
Spread the love

How to call JavaScript function in HTML without onclick? Though the most straightforward way is to use the onclick attribute, sometimes there are situations where we have to call a function without onclick.

The best way to call a JavaScript function in HTML without onclick is to use an event listener. It is a modern method of handling JavaScript events and help us to prevent tight coupling between HTML elements and JavaScript methods.

Here, In this article, we are going to share how to call JavaScript function in HTML without onclick by providing different methods, alternative ideas, code examples, and best practices. So bear with us and read to the end.

Table of Contents

  • Why Should We Avoid Onclick?
  • 5 Proven Methods to Call JavaScript Functions Without Onclick
    • 1. Using Event Listeners
      • output – How to call javascript function in html without onclick using addEventListener
    • 2. Using the onload Event
      • output
    • 3. Using CSS Pseudo-Classes
    • 4. Using setTimeout and setInterval
      • Here is an example with setTimeout:
      • Output
      • Example with setInterval
      • output
    • 5. Using MutationObserver
      • output
  • Summary Table of 5 Different Methods
  • Conclusion

Why Should We Avoid Onclick?

While onclick is simple and effective and is used by developers in most cases, there are situations where we have to avoid it. Here are the major cases:

  • Separation of Concerns: Keeping HTML and JavaScript separate for better code organization.
  • Reusability: Making functions reusable across different elements.
  • Readability: Enhancing code readability and maintainability.

5 Proven Methods to Call JavaScript Functions Without Onclick

1. Using Event Listeners

Today, event listeners are the most standard way to handle events in JavaScript. They allow us to attach a function to an element without using inline event attributes like onclick.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>How to call JavaScript function in HTML without onclick?</title>
</head>
<body>
    <button id="myButton">Click Me</button>

    <script>

        function myFunc() {
          console.log("Button clicked! On: "+ new Date().toLocaleString("en-US"));
        }
        
        // Add click event listener
        document.getElementById('myButton').addEventListener('click', myFunc);
    
    </script>
</body>
</html>
output – How to call javascript function in html without onclick using addEventListener
How to call javascript function in html without onclick – using addEventListener

You can also use an anonymous or inline JS function instead of a named function myFunc() like:

<script>
  document.getElementById('myButton').addEventListener('click', function() {
      console.log('Button clicked!');
  });
</script>

2. Using the onload Event

The onload event fires when the whole page is loaded. This can be used to automatically call a JavaScript function after the page loads without depending on user actions.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Call Function Without Onclick</title>
</head>
<body onload="pageLoaded()">
    <h1>Welcome to My Website coderstechzone.com</h1>

    <script>
        function pageLoaded() {
            console.log('Page fully loaded');
        }
    </script>
</body>
</html>
output
how to call javascript function in html without onclick - using onLoad event
How to call javascript function in html without onclick – using onLoad event
buymeacoffee

3. Using CSS Pseudo-Classes

You can combine CSS pseudo-classes with JavaScript to call a function based on user interactions, like hovering over an element. In this example, we use CSS along with the mouseover addEventListener. Here is the example code:

How to call JavaScript function in html without onclick – using CSS Pseudo-Classes

4. Using setTimeout and setInterval

You can call functions after a specified time interval or repeatedly at fixed intervals using the setTimeout and setInterval method respectively.

Here is an example with setTimeout:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS Call Function Without Onclick</title>
</head>
<body>
    <h1>Automatic Message</h1>

    <script>
        function showMessage() {
            console.log('This message appears in 2 seconds!');
        }

        // Making a 2 seconds delay
        setTimeout(showMessage, 2000);
    </script>
</body>
</html>
Output
How to call javascript function in html without onclick - using setTimeOut
How to call javascript function in html without onclick – using setTimeOut
Example with setInterval
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Call Function Without Onclick</title>
</head>
<body>
    <h1>Repeated Message</h1>

    <script>
        function showRepeatedMessage() {
            console.log('This message appears every 3 seconds! '+new Date().toLocaleString("en-us"));
        }

        // For 5 seconds change to 5000
        setInterval(showRepeatedMessage, 3000);
    </script>
</body>
</html>
output
How to call JavaScript function in html without onclick – using setInterval

Note

Use the clearTimeout() method to prevent the function from re-loading.

buymeacoffee

5. Using MutationObserver

MutationObserver is a powerful feature that allows you to monitor changes in the DOM and trigger functions automatically. You can target a node and execute your required code if any changes occur in the target node.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Call Function Without Onclick</title>
</head>
<body>
    <div id="myDiv">Watch me change</div>
    <button onclick="changeContent()">Change Content</button>
    <button onclick="changeColor()">Change Color</button>

    <script>
        function changeContent() {
            document.getElementById('myDiv').innerText = 'Content changed!';
        }
        function changeColor() {
            document.getElementById('myDiv').style.color = 'red';
        }

        // The HTML element that will be observed for mutations
        const targetNode = document.getElementById('myDiv');

        // Options for the observer - which mutation needs to check
        const config = { attributes: true, childList: true, subtree: true };

        // Callback function will execute once mutations are observed
        const callback = function(mutationsList, observer) {
            for(let mutation of mutationsList) {
                if (mutation.type === 'childList') {
                    console.log('Content changed!');
                }
                else if(mutation.type === 'attributes'){
                  console.log('Content attribute changed!');
                }
            }
        };

        // Create observer instance to a callback function
        const observer = new MutationObserver(callback);

        // Start observing the target for change
        observer.observe(targetNode, config);
    </script>
</body>
</html>

Note

If you want to stop observing then use observer.disconnect();

output
how to call javascript function in html without onclick – using MutationObserver

In this example, we target a div. Configure three types of mutations to be detected. If content or font color changes are detected, then a callback function will automatically be invoked. Check the change type and run the code accordingly.

Summary Table of 5 Different Methods

MethodDescriptionUse Case
Event ListenersAttach functions to events without inline attributesHandling user interactions
Onload EventCall functions when the page fully loadsInitializing scripts after page load
CSS Pseudo-ClassesCombine CSS and JavaScript for dynamic interactionsVisual effects based on user actions
setTimeout/setIntervalSchedule functions to execute after a delay or repeatedlyTimed actions or animations
MutationObserverMonitor and react to DOM changesDynamic content updates

Conclusion

Knowing how to call JavaScript function in HTML without onclick is an uncommon skill, and not all JS developers are interested about it at all.

So by using event listeners, the onload event, CSS pseudo-classes, setTimeout, setInterval, and MutationObserver –  we are able to create dynamic, organized, and maintainable code without difficulty.

These methods assist us hold our HTML and JavaScript code separate, making the code  cleaner and more efficient. Implement those techniques for your tasks to improve capability and the user experience. Happy Coding !!

Shawpnendu Bikash Maloroy
Shawpnendu Bikash Maloroy

๐Ÿ‹๏ธโ€โ™‚๏ธ Discover Code Blocks From 20+ yrs JS Expert
๐Ÿ’ฅ Asp.net C# Developer
๐Ÿ† Solution Architect
๐Ÿ‘จโ€โœˆ๏ธ Database Administrator
๐Ÿ“ข Speaker
๐ŸŽ“ MCTS since 2009

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Spread the love
ยซPrevious
Nextยป

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • 5 Lesser-Known JavaScript Functions
    5 Lesser-Known JavaScript Functions to Boost Your Coding Efficiency
  • 7 Weird JavaScript Tricks That Look Like Bugs
    7 Weird JavaScript Tricks That Look Like Bugs (#3 Will Shock You!)
  • Build a JavaScript Gamer Journal in 8 Lines
    ๐ŸŽฎ Build a JavaScript Gamer Journal in 8 Lines: Track Your Wins Like a Pro! ๐Ÿ†
  • JavaScript Pet Feeder Reminder in 7 Lines
    How to Code a Simple JavaScript Pet Feeder Reminder in 7 Lines: Feed Your Pet Like a Coding Boss! ๐Ÿถ
  • 10-line calculator JavaScript
    Build a Simple Calculator in JavaScript: 10 Lines to Wow Your Friends!

About-CodersTech Zone |  Contact |  Disclaimer |  Fact-Checking policy |  Affiliate Disclosure |  Privacy Policy

Copyright ยฉ 2024 CodersTechZone.com