javascript the debate between inline and traditional registration

Hey there, I'm a JavaScript beginner and currently learning about inline vs. traditional registration. I've managed to get code block 1 (inline) working perfectly fine, but unfortunately, code block 2 (traditional) isn't cooperating. Can someone help me figure out what's wrong?

<html>
<head>
<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/md5.js"></script>
<script>
function gethash() {
var name=prompt("Please enter your name","Harry Potter");
var hash = CryptoJS.MD5(name);
alert("Hello, " + name +".\nYour hash is " + hash)
}
</script>
</head>
<body>
<input type="button" onclick="gethash()" value="Get your hash" />
</body>
</html>

I've made an attempt at using traditional registration with the following code:

<html>
<head>
<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/md5.js"></script>
<script type="text/javascript">
function gethash() {
var name=prompt("Please enter your name","Harry Potter");
var hash = CryptoJS.MD5(name);
alert("Hello, " + name +".\nYour hash is " + hash)
}
document.getElementById('myname').onclick = gethash;
</script>
</head>
<body>
<input type="button" value="Get your hash" id="myname" />
</body>
</html>

Answer №1

When attempting to bind something using onclick, it seems that there is no element present at that particular point. To resolve this issue, consider moving that line of code to the bottom of the file.

If you check the browser console, an error message may appear similar to:

Uncaught TypeError: Cannot set property 'onclick' of null

The following adjustment should address the problem:

<html>
<head>
<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/md5.js"></script>
</head>
<body>
<input type="button" value="Get your hash" id="myname" />

<script type="text/javascript">
function gethash() {
var name=prompt("Please enter your name","Harry Potter");
var hash = CryptoJS.MD5(name);
alert("Hello, " + name +".\nYour hash is " + hash)
}
document.getElementById('myname').onclick = gethash;
</script>

</body>
</html>

An alternative approach involves utilizing window.onload. By utilizing this method, you can ensure that the JavaScript code executes only after the entire page has finished loading.

window.onload = function() {
    document.getElementById('myname').onclick = gethash;
};

Answer №2

If you try to bind an event using

document.getElementById('myname').onclick = gethash;
, and the element you're targeting does not yet exist, it won't work as expected.

An alternative approach is to wrap your code in an onload event handler like this:

<html>
    <head>
        <script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/md5.js"></script>
        <script type="text/javascript">
            function gethash() {
                var name=prompt("Please enter your name","Harry Potter");
                var hash = CryptoJS.MD5(name);
                alert("Hello, " + name +".\nYour hash is " + hash)
            }
            window.onload = function() {
                document.getElementById('myname').onclick = gethash;
            }
        </script>
    </head>
    <body>
    <input type="button" value="Get your hash" id="myname" />
    </body>
</html>

The onload method may not be the most efficient way since it waits for all resources to load before executing. Consider using the DOMContentLoaded event or explore libraries like jQuery for better cross-browser support.


By separating your presentation from logic, you can maintain cleaner code. Try to avoid inline event handlers for better organization.

Answer №3

sachleen provided the correct solution (the code below is functional) - although it may be simpler to relocate the entire javascript block to the bottom of the body section:

<html>
<head>
    <script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/md5.js"></script>
</head>
<body>
    <input type="button" value="Get your hash" id="myname" />
    <script type="text/javascript">
        function gethash() {
            var name=prompt("Please enter your name","Harry Potter");
            var hash = CryptoJS.MD5(name);
            alert("Hello, " + name +".\nYour hash is: " + hash)
        }
        document.getElementById('myname').onclick = gethash;
    </script>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Problem with Submitting Form using Search Bar

I've tried everything, but I can't seem to get this search form to submit. <div id="search_bar_container" style="z-index:99999"> <div class="container"> <form action="tour-list-search-results.php" method="post" name="searc ...

Parent function variable cannot be updated within a $.ajax call

I'm facing an issue with pushing a value from inside an ajax call to an array located outside of the call but still within the parent function. It appears that I am unable to access or update any variable from inside the ajax success statement. Any as ...

Issue with TableHead not functioning properly when sorting is requested

I'm currently facing an issue with my table that has clickable row headers for sorting functionality using the onRequestSort function. Unfortunately, it seems like this feature is not working as expected. I have implemented the sorting logic using rea ...

Why does `window.location.reload()` only refresh the home page and not the other pages when using Angular?

After transitioning from the home page to the menu page, I expect the menu page to refresh automatically once. However, when implementing the code below, the home page is refreshed first before navigating to the menu page without an auto-refresh. 1)Initia ...

The ClearInterval() function does not take effect instantly

I've implemented a Carousel with an auto-toggle feature using the setInterval() function to switch between tabs every 4 seconds. However, I now need to stop this automatic toggling when a specific tab is clicked. You can find the HTML and jQuery for ...

Determine a deeper hue using Javascript

Is there a way to adjust this calculation to achieve a darker color rather than a brighter one? function increase_brightness(hex, percent){ // strip the leading # if it's there hex = hex.replace(/^\s*#|\s*$/g, ''); // ...

Vue JS - Unable to locate module (datepicker)

Today marks my first time delving into the world of vue.js, and as expected, I've encountered an error that has me stumped. I recently incorporated the v-md-date-range-picker module into my project: (. The setup instructions provided me with the f ...

What changes can be made to this function in order for the arches to be positioned directly in front of the camera?

I devised a method that arranges arches in front of a camera, side by side: <!-- HTML --> <a-curvedimage v-for="(value, index) in model" :theta-length="42" :rotation="setThumbsRotation(value, index)"> </a-curvedimage> <a-camera ...

Error 400: Token Obtain Pair request failed in Django REST with simpleJWT and Vue 3 composition API

I'm encountering an issue with obtaining the refresh and access tokens when sending a form from my Vue app to the Django REST API. CORS has been enabled, and signing up through the REST API page or using Postman doesn't pose any problems. However ...

Problem with deleting or substituting symbols and character codes within a String

I am attempting to send an object called dataO from Node.js/Express/EJS to the client side. On the Node.js script side: var dataO = {"first":[20000, 14000, 12000, 15000, 18000, 19000, 22000], "second":[12000, 11000, 18000, 12000, 19000, 14000, 26000]}; var ...

When using react, it is not possible to have a <span> element as a child of a <

I designed a custom select dropdown feature for use in a redux-form within a react-redux application. The dropdown functions well, with no performance issues, but I am encountering a warning in the browser. Warning: validateDOMNesting(...): <span> c ...

The most effective method for transferring asynchronous data to pages in Next.js

My current directory structure: - components - NavBar - Header - Layout - pages - pages - demo.js - _app.js - index.js // index.js import React from 'react'; import NewLayout from "../../components/NewLayout/NewLayou ...

What is the best way to switch the CSS style of a button that has been mapped

I'm currently working on toggling the CSS class for an individual button that is created from a mapped array. Although my code is functional, it toggles the CSS class for all buttons in the mapped array instead of just the one selected. ...

How can I execute a synchronous MongoDB query in Node.js properly?

When utilizing the Node.JS driver for MongoDB, I am interested in executing a synchronous query. Here is an example of what I am aiming to achieve: function retrieveSomething() { var database = new mongo.Db("mydatabase", server, {}); database.ope ...

The type does not have a property named 'defaultProps'

I have a Typescript React class component structured like this: import React, { Component } from 'react'; interface Props { bar?: boolean; } const defaultProps: Partial<Props> = { bar: false, }; class Foo extends Component<Props& ...

Having an issue with transmitting information to the database using ajax and Laravel

I am currently working on creating a drag and drop list that can be sorted. Each time an element is dropped into a new area, the order of the list should change accordingly. I am implementing this using AJAX and Laravel, but encountering an error when drop ...

Ways to properly link a webpage using the anchor tag's href attribute

I am currently working with reactjs and bootstrap, and I am trying to display and collapse an unordered list within a list item (nested unordered list). Bootstrap provides a useful collapse feature for this purpose. By using an anchor tag with a data-toggl ...

Node.js threw an error when trying to download a tarball, displaying a status code of

While attempting to install various modules in Nodejs using NPM, I encountered a situation where the installation process failed and returned an error: Error: 403 status code downloading tarball This same issue happened again when I tried to install node ...

Tips for extracting certain characters from a URL and saving them as an ID using JavaScript

Consider this scenario where I have a specific URL: http://localhost:3000/legone/survey/surveyform/form11/03141800300000030001 In order to achieve the desired outcome, I aim to extract and store different parts of the URL into designated IDs. Specificall ...

Encountering error while trying to set up Hardhat using npm - "npm ERROR! Invalid URL code"

PS C:\Users\jawad\OneDrive\Desktop\NFT Project> npm install --save-dev hardhat npm ERR! code ERR_INVALID_URL npm ERR! Invalid URL npm ERR! A complete log of this run can be found in: C:\Users\jawad\AppData\L ...