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

Guide on setting up a MEAN stack application to run on port 8080

I am brand new to the mean stack development environment. I'm attempting to configure my root domain name to display the app directory once I enter the command grunt, but the only way it currently works is at website.com:8080/!#/. How can I get it to ...

Could someone break down for me the behavior exhibited within this method?

Hello there, I'm a beginner so please forgive me for any lack of knowledge. const example = { myFunction(){ console.log(this); }, myFunction2(){ function myFunction3(){ console.log(this) } return ...

Angular ng-if directive contains a specific class

I am trying to create a directive that will only be active when an element has a specific class. I have tried the following code: <feedback-analytics ng-if="$('#analyticTab').hasClass('active')"></feedback-analytics> Unfor ...

What are the steps to install the LTS release of NodeJS if Node 10 is already installed on my system?

Several weeks ago, I installed Node version 10.11 on my computer. However, a repository I am working with requires me to have the LTS version of Node, which is currently 8.12. If I download the LTS version, will it interfere with my existing install, or ...

Using Axios and Typescript to filter an array object and return only the specified properties

I'm currently working on creating an API to retrieve the ERC20 tokens from my balance. To accomplish this, I am utilizing nextjs and axios with TypeScript. However, I'm encountering an issue where the response from my endpoint is returning exces ...

Unpacking and reassigning variables in Vue.js 3 using TypeScript

I am working with a component that has input parameters, and I am experimenting with using destructuring assignment on the properties object to reassign variables with different names: <script setup lang="ts"> const { modelValue: isSelected ...

Resizable table example: Columns cannot be resized in fixed-data-table

I've implemented a feature similar to the Facebook example found here: https://facebook.github.io/fixed-data-table/example-resize.html You can find my source code (using the "old" style with React.createClass) here: https://github.com/facebook/fixed- ...

Exploring the capabilities of the Next.js router and the useRouter

import { routeHandler } from "next/client"; import { useRouteNavigator } from "next/router"; const CustomComponent = () => { const routerFromHook = useRouteNavigator(); } export default CustomComponent; Can you explain the disti ...

Guide on implementing jQuery Validation plugin with server-side validation at the form level

Does anyone have a suggestion for how to handle server-side validation errors that occur after passing the initial client-side validation on a form? $("#contact_form").validate({ submitHandler: function(form) { $.ajax({ type: 'POST', ...

The hot loader is replicating code multiple times instead of conducting hot swapping

Every time I make a change in a component, webpack recompiles and React hot swaps the module over. However, I've noticed that my code runs multiple times after each hot module swapping occurrence. For example, if I make a change once, the functions ru ...

Update google maps markers and infoBubbles dynamically with ajax

I am currently using asp mvc in conjunction with jquery and the google maps api to showcase and update various locations on a map. Main Objective: Utilize markers to mark multiple locations Display brief information about these locations using info ...

What is the process for sending a selected option using AJAX?

Using Ajax within Laravel to save data involves a form with input fields and a select option. Here is the form structure: <form class="forms" method="get" action=""> {{ csrf_field() }} <div class="form-group row ...

Tips for displaying content when clicking on the opener containing tables or div elements

This is a snippet of JavaScript code $(document).ready(function () { $(".show-content").hide(); $(".opener").click(function () { $(this).parent().next(".show-content").slideToggle(); return false; ...

Incorporating middleware in Next.js to remove route protection

Looking to remove the protection for the login page, and here is how my folder structure looks: https://i.stack.imgur.com/klPYV.png This is the middleware I am using: import { NextResponse, NextRequest } from "next/server"; export async functi ...

How can we rearrange the positions of three items in an array?

I am dealing with a function that returns an array of objects structured like this const allGreen = _.filter( sidebarLinks, side => !isServicePage(side.slug.current) ); https://i.stack.imgur.com/dR8FL.png I am attempting to rearrange the positions of ...

Ways to provide information to an rxjs observer

It appears that most people find observers to be a piece of cake, but I personally struggle with them. I am trying to set up an observable that can receive a number input after it has been created, triggered by pressing a button. However, all the examples ...

Encountering an issue when trying to retrieve the "createdAt" property in Cloud Code using the Parse Framework

I am working with Cloude Code to develop a more complex query, but I am having trouble accessing the automatically created "createdAt" property by Parse. Here is my code: Parse.Cloud.define("get_time", function(request, response) { var query = new Par ...

The data is not being successfully transmitted to the controller method through the AJAX call

In my JavaScript file, I have the following code: $(document).ready(function () { $('#add-be-submit').click(function (event) { event.preventDefault(); $.ajax({ type: 'POST', url: '/snapdragon/blog/new&apos ...

Why can't we use percentages to change the max-height property in JavaScript?

I am currently working on creating a responsive menu featuring a hamburger icon. My goal is to have the menu list slide in and out without using jQuery, but instead relying purely on JavaScript. HTML : <div id="animation"> </div> <button ...

javascript verify that the input is a valid JSON object

Seeking assistance with an if statement that checks for a json object: updateStudentData = function(addUpdateData) { var rowDataToSave; if(addUpdateData.data.row) { rowDataToSave = addUpdateData.data.row; } else { rowDataToSav ...