Javascript function failing to execute upon page load

I don't have much experience with JavaScript, but I found the following code in a .htm file. The function doesn't seem to be triggering when it should; It is supposed to activate when the page is directly opened i.e

www.site.com/12345.htm 

This will change the URL to

site.com/#12345.htm

and load the necessary scripts and stylesheets.

The function shouldn't be triggered when accessed indirectly. For example, going to www.site.com/ shouldn't trigger it as the index.htm already loads the css/script instantly.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title> Introduction </title>
<script type="text/javascript">
    function isTOCLoaded() {
        //this function loads the specific topic within the application if accessed independently
        //for example, opening the topic .htm file or through search engine links
        var url = window.location.href;
        var baseUrl = url.substring(0, url.lastIndexOf("/") + 1);
        var topicFile = url.substring(url.lastIndexOf("/") + 1)
        var newUrl = baseUrl + "#" + topicFile;
        location.href = newUrl;
        return false;
    }
</script>
</head>
<body>
<h1 id="t57117" class="heading1">Introduction</h1>

<input id="topicId" type="hidden" value="57117" />
<input id="topicDescription" type="hidden" value="Introduction" />
<input id="footer-modified" type="hidden" value="Last modified: 17/12/2015 8:18:59 a.m." />
</body>
</html>

Answer №1

If you want your function to be evaluated, you must remember to call it:

<title> Introduction </title>
<script type="text/javascript">
    function isTOCLoaded() {
        //this function for loading the topic within the application if loaded by itself
        //i.e. open the topic .htm file or as search engines link
        var url = window.location.href;
        var baseUrl = url.substring(0, url.lastIndexOf("/") + 1);
        var topicFile = url.substring(url.lastIndexOf("/") + 1)
        var newUrl = baseUrl + "#" + topicFile;
        location.href = newUrl;
        return false;
    }

    // ADDED: run the function
    isTOCLoaded();
</script>
</head>

When working with JavaScript, remember that the function keyword is used to simply declare a function for future use. The function's contents are not executed until the function is called for the first time.

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

Incorporate text onto an image using Semantic UI

Currently, I am utilizing Semantic UI to display images. While it is functioning well for me in terms of adding text near the image, I desire to have the text positioned on top of the image. Ideally, I would like it to be located on the lower half of the i ...

Voice recognition feature in the latest version of Chrome on Android devices

When using a PC with Chrome 25 (non beta), I see a microphone icon that prompts for input when clicked. After speaking, my alert call is successfully executed. However, on a Galaxy Note smartphone with Chrome 25 and an Android 4.04 operating system, the sa ...

How to create a stunning Bootstrap Jumbotron with a blurred background that doesn't affect the

I need help making my Jumbotron image blurry without affecting the text inside it! Below is the code from my index.html and style.css files. Any assistance would be greatly appreciated. body { background-image: url(bg1.png); background-repeat: repea ...

What is causing the regular expression to fail when using the OR operator?

Here is the code snippet I've been working on: function toCamelCase(str){ var rest = str.replace((/-/)|(/_/)g, "") ; document.write(rest); } toCamelCase("the-stealth_warrior"); When running this code, I receive an error message: Uncaught Syntax ...

Leverage JQuery Mobile for smooth sliding and effortless deletion of list elements

Currently, I am testing a JQuery Mobile webpage that features a simple list setup: Upon clicking the list items, they get highlighted and their ids are saved in a local array. Is there an easy (or not so easy) way to transition the selected elements slidi ...

What is the best way to eliminate a trailing backslash from a string?

Currently, I am iterating through a list of Discord server names in node.js. The goal is to create a php file that contains an array structured like this: <?php $guildLookup = array( "164930842483761" => "guildName1", "56334 ...

Obtain data with matching JSON values in a REACT application

Recently, I received a JSON file that looks something like this: [ { "symbol": "A", "name": "Agilent Technologies Inc", "exchange": "NYSE", }, { "symbol": "AAC ...

What methods can be used to avoid regular expressions when searching for documents in MongoDB?

I am using a simple regular expression-based search in MongoDB like this: router.get('/search', function (req, res, next) { var text = req.query.text; collection.find({text: new ReqExp(text, 'ig')}, function (err, result) { ...

The closing brackets in PHP substr() function are causing style issues

Here's the scenario: I entered a large amount of content in a text editor (WordPress). Now, I want to display this content on my homepage using PHP queries. In order to limit the content size to 100-200 characters, I used the substr() function i ...

Why isn't the CSS pseudo ::before functioning properly on an Icon element?

I am encountering an issue with displaying a vertical line to icons in my HTML code. The structure of the HTML is as follows: Below is the HTML code snippet: <div class="newsTimePeriod item-One"> <h3>News</h3> ...

Using Javascript and jQuery to validate strings within an array

My existing jQuery code works perfectly by returning true if it matches the specified name. jQuery(function($) { var strings = $(".user-nicename").text(); if (strings === "name1") { $('.mention-name').hide(); $('.se ...

Issue with parameter functionality not working as expected

This code snippet is not functioning as expected. I am trying to extract and print the values from the URL parameter file:///C:/Users/laddi/Desktop/new%201.html?t=vindu&b=thind function GetURLParameterValue(param) { var pageURL = window. ...

Creating audio streams using react-player

I am currently working on integrating the react-player component from CookPete into my website. However, I am facing a challenge in setting up multiple audio streams. Additionally, I want to include both DASH and HLS video streams but adding them as an arr ...

ng-required is ineffective when used with number inputs that have a minimum value requirement

In my form, I have implemented a checkbox that, when checked, toggles the visibility of a div using AngularJS's ng-show. Within this div, there is an input field of type "number" with a validation setting of min="10000". I am trying to prevent the f ...

XSL fails to display HTML tables

I am having trouble displaying information from an XML file about hotels using XSL on a webpage without HTML tables. Despite searching through numerous posts on StackOverflow, I cannot seem to pinpoint where I may have gone wrong. Here is an excerpt from ...

Adjust the initial scroll position to - apply overflow-x: scroll - on the specified element

I have an image that can be scrolled to the right on screens that do not fit the full width, but I want the center of the image to be displayed first instead of the left side. Below is my React code: import React, { useEffect, useRef, useState } from &qu ...

What is the best way to display tip boxes for content that is added dynamically?

One of the challenges with my web page is that dynamically added content does not display tipboxes, unlike items present since the page load. I utilize the tipbox tool available at http://code.google.com/p/jquery-tipbox/downloads/list. To illustrate the i ...

Locate and retrieve a document by its unique identifier in MongoDB, and then store its information in an array

I am working with two models: Meal and Ingredient. Let's take a look at their schemas: const mealSchema = new Schema({ title: { type: String, required: true }, image: { type: String, required: false }, ingredients: [{ ingredient: { ...

Are there other options besides Chrome Frame for enhancing Raphael performance on Internet Explorer?

Currently, I am using Raphael 2.1 to simultaneously draw 15 lines, each consisting of 50 two-pixel paths. The performance is optimal in Safari and Chrome, acceptable in Firefox, subpar in Opera, and struggles in IE9. Despite Microsoft's claim that SVG ...

What steps can I take to prevent constantly re-fetching a disabled CSS file?

I'm currently in the process of implementing a dark theme on my website, and my current method involves using 2 style sheets: <link rel="stylesheet" type="text/css" href="/flatly.css"> <link rel="stylesheet& ...