Are you making a novice mistake with Javascript variables?

Let me preface this by stating that the code provided is not my own. As a novice hobbyist coder delving into the realm of Javascript, I have turned to a book in hopes of expanding my knowledge. However, a setback has emerged as the publisher's website lacks the necessary files for the exercises within the book.

The aim of the code snippet below is to display the contents of the 'str' variable upon execution. Yet, instead of the expected output, all I see is a blank screen when running it. Despite scouring for glaring typos, none have surfaced. Initially setting up an HTML document like so:

<html>
<head>
<title>Variable</title>

<script type = "text/javascript" src = "variable.js">
obj.innerHTML = str + ":" + typeof str;
</script>   

<body>
<div id = "panel"> </div>
</body>

I proceeded to input the output code in Notepad and saved it in the same directory as the HTML file. Additionally, saving the code as a JavaScript file in that very location.

The aforementioned output code is as follows:

 function init()
{
    //STATEMENTS TO BE EXECUTED GO HERE
var str = "Text Content in Javascript";

obj.innerHTML = str + ":" + typeof str;
}
document.addEventListener( "DOMContentLoaded", init, false);

Based on my limited understanding of JavaScript, it appears that the script responsible for displaying the result remains unseen. Puzzlingly enough, the reason behind this eludes me – either due to oversight or some other blatantly obvious factor. Where exactly does the missing piece lie?

Answer №1

Wow, there's so much happening in this code!

  • No sign of <!DOCTYPE html>
  • The closing tag </head> is missing
  • The closing tag </html> seems to have disappeared
  • Code duplication issue with the script tag calling variable.js and your variable.js file.
  • Looks like you forgot to assign a value to the obj variable in variable.js

Here's some functional code for you to review:

HTML Layout

<!DOCTYPE html>
<html>
  <head>
    <title>Variable</title>
    <script src="variable.js"></script>
  </head>
  <body>
     <div id="panel"></div>

     <script>document.addEventListener( "DOMContentLoaded", init, false);</script>
  </body>
</html>

Contents of variable.js file

function init() {
    //CUSTOM CODE GOES HERE
  var str = "Text Content in Javascript";

  var obj = document.getElementById("panel");
  obj.innerHTML = str + ":" + typeof str;
}

Enjoy exploring and learning more!

Answer №2

There is a script tag missing in your code.

<script type = "text/javascript" src = "variable.js"></script>
<script>
element.innerHTML = text + ":" + typeof text;
</script>   

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

Develop an onclick function with an href attribute

I am interested in transforming links into AJAX versions whenever possible. To achieve this, I plan to implement a function called replaceLinks that will add an onClick handler to each link on the page and trigger ajaxPageWSM(href). This is what I currentl ...

Using JavaScript to reduce, group, and sum nested objects

I'm a third-year student working on my first internship project and struggling with organizing and aggregating data from a JSON object. The goal is to group the data by name, calculate total weight per name, and sum up the grades for each entry. I&apo ...

Tips for merging two JSON files to create a single associative array

How can I merge two similar JSON files in JavaScript, where elements from each are combined into a new associative array in a specific pattern? For example: var JSON1 = {'Item 1':123, 'Item 2':234, 'Item 3': 345} var JSON2 = ...

Results from AWS DynamoDB Scan operation

I am currently utilizing the AWS JavaScript SDK for DynamoDB, and executing a scan operation to retrieve a list of items from a table. The returned results show that each value is enclosed within an attribute type key: For instance: An anticipated result ...

Why is my Ajax utilizing PHP _POST not functioning as expected?

I am facing an issue with the JavaScript code below: <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js'></script> <script> function deletUserInfo(id_user){ console.log(id_user); ...

Elements added through d3 and jquery are not showing up in the SVG

I am experiencing an issue with a line chart created using d3. I am appending text elements to each datapoint (svg circle element) using d3 and jquery, but the elements are not appearing on the chart. Interestingly, when I manually edit the HTML in Chrome ...

What is the best way to choose "this" element in Angular?

Within my template, I have 5 buttons each utilizing the same ng-click function. These buttons essentially function as a tabbed navigation system, where clicking on one button directs the user to that specific tab's content pane. All of these buttons c ...

Issue with BackboneJS TypeError

I attempted to use the example below, but I encountered an error stating "TypeError: _.has is not a function". Example: I have experimented with different versions of jQuery and Backbone (uncompressed), yet the same error persists. Can anyone offer assis ...

Issues arising with AJAX POST requests in C# programming language

I am facing an issue where my C# function is not being called from an Ajax script. I have set up the Ajax post request to call the function, but it seems like there is some error preventing it from executing. Can anyone help me figure out why? Below is th ...

Replace Picture as you Scroll

Is it possible to swap images based on scroll position? For instance: When scrolling 100px, display img1.jpg When scrolling 200px, display img2.jpg When scrolling 300px, display img3.jpg Here's an example of what I'm looking for. Any suggest ...

Refining an object by using a parent key as a filter criterion (JavaScript)

Refined JSON Data Check out this unfiltered JSON object that I am working with: info = [ {id: 1, name: "home", parent: 0, active: 1, order: 0}, {id: 2, name: "dashboard", parent: 0, active: 1, order: 1}, {id: 3, name: & ...

Transferring information between app.js and HTML files

My initial route with Node.js and Express is responsible for determining the client's language : var express = require('express'), app = module.exports = express(), server = require('http').createServer(app), io = requ ...

Failed to fetch user id from server using Ajax request

I am facing an issue with my form that includes a text input field and a button. After submitting the form, I extract the value from the user field and send an ajax request to ajax.php to retrieve the userID from the server. The server does return a value, ...

Trigger a sound or notification whenever a specific user sends a message on a pre-existing website

As a user of a website featuring a chat widget for communication with instructors, I have a specific request. I would like to receive an audio notification whenever the instructor sends a message, and perhaps even a browser notification if possible. It is ...

What is the best way to import assets from an NPM-powered package in a PHP composer-based package?

First and foremost, let's clarify that this is not a question about incorporating an NPM package as a dependency of a Composer package. Direct usage of NPM or a composer plugin can easily solve that issue. If we have loaded an NPM package as a depend ...

Create a stunning animation where the div moves gracefully from the center to the bottom right corner of the screen and remains

I am currently exploring ways to animate a div that starts in the center of a page within another div that is centrally located. The main challenge I face is that initially, this div should not have an absolute position. Ideally, I would prefer it not to s ...

Creating OneToMany references between existing MongoDB documents is a straightforward process that involves updating the relevant fields in

My first encounter with MongoDB has left me puzzled about creating references between documents that are already in the database. Unlike SQL, I am unsure how to establish relationships between collections. I have two collections: Films and Actors. The Fil ...

Creating a responsive form with live updating using ReactJS and utilizing double inputs for better

Currently, I am working on updating a form with double input fields. The aim is for users to be able to click an 'add' button and update the state with their values, while ensuring that the two input fields are "connected". To better illustrate m ...

Protractor never-ending cycle

In my previous question, I encountered an issue with clicking a button until it becomes disabled. Initially, the solution was as follows: var nextPage = function () { if (element(by.css('[ng-click="vm.nextPage()"]')).isEnabled()) { e ...

Extracting CSS data and storing it in a SQL database

Hello there, I've created a div using CSS like this: echo '#'. $pess2['naam'] .' { width: 190px; height: 90px; padding: 0.5em; float: left; left:'. $pess2['left'] .'px; top:'. $pess2['top'] ...