JavaScript alert: element does not exist

Check out my code snippet below. The inline JavaScript alert works fine, but the external one isn't firing. Every time I reload the page, I'm greeted with a console error message saying "TypeError: tileBlock is null". Any suggestions on how to resolve this? I prefer not to resort to writing all of my JavaScript event handlers inline. Thank you for your help!

#tileBlock {
    position: fixed;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        background-color: #0b0b0b;
        background-position: center;
        background-repeat: no-repeat;
        background-image: url(photo.jpg);
        border: 20px solid #fff;
        background-size: cover;  
    }

    @media (max-width: 400px) {
      #tileBlock {
        border-width: 8px;
      }
    }

<body>
  <div class="wrapper" id="tileBlock" onclick="alert('You clicked (inline)')"></div>
</body>

var tileBlock = document.getElementById('tileBlock');
tileBlock.onclick = function() {
    alert('you clicked(external script)');
}

Answer №1

To implement this functionality, make sure to include the jQuery library and use the following code:

$('#tileBlock').onclick(function(){
    alert('you clicked(external script)');
});

I have personally tested your code and it is functional (the jQuery code is not mine). Feel free to try it out here: http://jsfiddle.net/XcsN/evK3v/

Answer №2

Feeling grateful for the guidance on implementing a window.onload event. Much appreciated, everyone!

window.onload=function(){
var tileBlock = document.getElementById('tileBlock');
tileBlock.onclick = function() {
    alert('you clicked yes');
}
};

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

Describing a function in Typescript that takes an array of functions as input, and outputs an array containing the return types of each function

Can the code snippet below be accurately typed? function determineElementTypes(...array: Array<(() => string) | (() => number) | (() => {prop: string}) | (() => number[])>) { /// .. do something /// .. and then return an array ...

Utilizing a Promise in NodeJS and Express to effectively capture the writing functionality of the HTTP module

Currently, I am in the process of developing an Express application with the following components: NodeJS v8 express (latest version) As I delved into the workings of the onHeaders module and observed how it alters the HTTP headers, I became keen on lev ...

Utilizing @casl/vue in conjunction with pinia: A guide to integrating these

I'm currently facing an issue with integrating @casl/ability and Vue 3 with Pinia. I'm unsure of how to make it work seamlessly. Here is a snippet from my app.js: import { createApp } from "vue" const app = createApp({}) // pinetree i ...

Store and retrieve user input using JavaScript or JSON

Can someone please assist me in finding a solution to this problem? I have 3 input fields where users can type in their answers. There is also a "SAVE" button that allows users to download their input values into a file.txt. Additionally, there is a "choos ...

There was an error with validation in Graphql that was of an undefined type

Running a gql query on a React app with default variables is causing an error. The specific error message is: Error: GraphQL error: Validation error of type FieldUndefined: Field 'firstname' in type 'HealthcareWorkersPage' is undefin ...

Cypress test never finishes when an unforeseen alert is triggered in the system during the test

When a web application unexpectedly throws an error using an alert box, the Cypress test becomes stuck indefinitely. The test will not complete or fail until the user manually closes the browser or clicks on the OK button within the alert box. https://i.s ...

Add to Firebase reference using AngularFire

Imagine I'm constructing a never-ending scroll of articles. The article's ID is obtained from the URL: var id = $stateParams.id; I aim to startAt that specific index in my Firebase collection and restrict it to 10 items: var limit = 10; var a ...

Is it possible to retrieve only the attributes in an array?

https://i.sstatic.net/E1DMb.png I am working with an array that has properties embedded within it. I am wondering if there is a method to separate out these properties from the array data and transform them into a distinct object containing only the prope ...

File Upload yields a result of 'undefined'

Currently, I am utilizing Express File Upload. When attempting to send a post request to it, the error-handler returns an error indicating that no files were found. Upon logging console.log(req.files), it shows as undefined, causing the error to be sent ba ...

Upon running `npm start`, an unexpected token error arises in the file originating from a local

After developing my first-app with the help of create-react-app, I incorporated some components from Material-UI. Everything was running smoothly when I launched it using npm start. Upon completion, I decided to extract the nice-component into its own fol ...

Experiencing a glitch with the Realtime Database feature on Firebase

// db.js file import * as firebase from "firebase/app" import "firebase/database" const config = { apiKey: "" ... } const db = firebase.initializeApp(config) export default db // App.vue ...

Having issues with the functionality of Bootstrap 4 popover?

In my Spring MVC web project, a Bootstrap popover appears when the help icon is clicked. However, on the first click, the popover opens and moves away from the icon. After closing it and clicking again, the popover correctly positions itself. When I chan ...

Tips for customizing the appearance of popup windows

I want to enhance the appearance of my popup window by applying a different format for opening it. How can I style it so that it looks visually appealing when the popup window opens? You can find below the source code I am working with: HTML: <div onM ...

Styling text using CSS depending on the displayed text

Utilizing Awesome Tables (AT), I am extracting data from a Google Sheets document to display on a website. The HTML template in the sheets is used for formatting the data, specifically focusing on the table output with inline CSS styling. Since the templat ...

Personalize Your Highcharts Legend with Custom HTML

Currently, I am working on a project with a highcharts graph where I need to gather data from the user regarding each line displayed. My goal is to include a text input box next to each label in the legend that relates to the series name. Once the user ent ...

Update the value of a JavaScript variable in an HTML template by targeting the element with a specific

Within my testFile.html HTML file, the following code is present: <div id="image-type-placeholder">marinaa</div> In my JavaScript file: const CourseImageUpload = BaseComponent.extend({ /** * @property {function} */ templat ...

Creating a banner image that scrolls while maintaining a fixed size

I'm looking to add a banner image with a scrolling effect as users navigate down the page, but I'm not sure what this technique is called. An example of what I'm trying to achieve can be seen on this site. As the user scrolls down, the res ...

The index type 'X' is not allowed for use in this scenario

I encountered an issue in my TypeScript code: error message: 'Type 'TransitionStyles' cannot be used as an index type.' I'm wondering if there's a way to modify my interface so that it can be used as an index type as well: ...

Expand the video comparison slider to occupy the entire width and height

I am striving to develop a video comparison slider that fills the height and width of the viewport, inspired by the techniques discussed in this informative article: Article Despite my efforts, I have not been successful in achieving this effect so far a ...

The step-by-step guide on displaying API choices in an Autocomplete feature and keeping them up

Having trouble with updating autocomplete options. An error message pops up in the console log when I try to deselect a tag or select a new one: MUI: The value provided to Autocomplete is invalid. None of the options match with [{"catName":{&qu ...