Trigger a JavaScript function upon clicking a link

Is it possible to have a CMS that loads articles using ajax, where the article is loaded through a function with parameters, and when a certain link is clicked, it redirects to the target page and launches the function on that page? For instance, let's say there is a function called loadArticle(articleID). When this function is triggered, it hides the div containing the article list and displays a specific article. Is there a way to call this function through a link, like:

<a onArticlePageLoad="loadArticle(15)" href="./articles">Title</a>


For example, on a page named page.html, there is a link that redirects to page2.html. Upon clicking this link, how can we load page2.html and execute a function called foo within page2.html?

Answer №1

ChristianF mentioned the importance of having an identifier on your link in order for this function to work properly. Here is the function:

function executeHashtag(hashtagString, action){
if (location.hash == hashtagString) {
action();
}
}
/* Receives: STRING -- Starting with '#'
 *            FUNCTION -- The function to be executed if the above string is found in the URL

Now, on the page linked as page2 with function foo execution and onload event handling:

window.onload = function (){

executeHashtag("#foo", foo());
executeHashtag("#bar", bar());
... //Include more cases as needed, just ensure that corresponding functions exist :)
}

Answer №2

One way to handle this is by creating a function that runs when page2.html loads, either at the end of the body or using the onload event.

Answer №3

It seems that in order to achieve the desired functionality, an onload event on page2 will be necessary, which should dynamically change the function called based on the link clicked on page1.

One possible solution could be:

page1:

<a href="page2?A">page2 case A</a>
<a href="page2?B">page2 case B</a>

page2:

<script type="text/javascript">
    window.onload = function updateFunction(){
        var queryString = window.location.search;
        if (queryString == "A") {
           functionA();
        } else {
           functionB();
        }
    }
</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

My AJAX requests do not include any custom headers being sent

I'm facing an issue with making an AJAX request from my client to my NodeJS/ExpressJS backend. After firing the request, my backend successfully receives it but fails to recognize the custom headers provided. For example: $.ajax({ type: " ...

Experience real-time updates on webpages with Node.js and Socket.io

Seeking to integrate real-time push notification updates from a node.js server to the browser client. Explored socket.io at http://socket.io/docs/rooms-and-namespaces/ The business requirement involves users viewing a page with customer information and o ...

Display an alert using Ajax when updating the database or inserting a new row

Hi there! I am currently looking for an ajax script that can update the count of unread messages without having to refresh the entire page. Additionally, I am also interested in a feature that can subtract from the count when a message is clicked, simila ...

Instruction failed to produce HTML output

Currently facing a challenge with my code - I have a dynamically created span (via ng-repeat). <span my-size id="abc"></span> <span my-size id="def"></span> <span my-size id="ghi"></span> The goal is to extract the id ...

Heroku is showing an Error R10 (Boot timeout) message, indicating that the web process was unable to bind to the designated $PORT within one minute of launching

Encountering an error while trying to deploy my first node project on Heroku. Here is the error message: 2020-09-29T04:24:09.365962+00:00 app[web.1]: production 2020-09-29T04:24:09.415266+00:00 app[web.1]: server is listening at port 40890 2020-09-29T04:24 ...

Customizing the color of cells in an HTML table within a JSON based on their status

Would you like to learn how to customize the color of cells in an HTML table based on the status of a college semester's course map? The table represents all the necessary courses for your major, with green indicating completed courses, yellow for cou ...

Please refresh the page in order to utilize the newly updated cookies

I have a specific process that involves: A button triggers the function fcn1 and redirects to a page called p1 Function fcn1 retrieves 6 strings from a backend SQL database The 6 strings are then stored in cookies Page p1 reads the 6 cookies and displays ...

Why does my ajax request show the result in the php file rather than redirecting to the html page?

I've developed a series of AJAX functions that retrieve data from a PHP file. However, one of the functions redirects to the PHP file to fetch data but fails to return to the HTML page for data insertion. Here is the code used to fetch a table from a ...

Unable to show message upon form submission with ajax

I'm attempting to use AJAX to submit a form in CodeIgniter. The form values are being saved in the database, but the response set in the controller isn't displaying in the console.log or alert within the AJAX code. Form Code <form class=" ...

There were no visible outputs displayed within the table's tbody section

import React from 'react'; export default class HelloWorld extends React.Component { public render(): JSX.Element { let elements = [{"id":1,"isActive":true,"object":"Communication","previ ...

The Feedback Form jQuery is not providing any data

I'm facing an issue with my html page that includes an ajax query to a php file. The purpose of this php file is to send a message and then return a response to the ajax query. However, no matter what I try, I am unable to receive any response from th ...

Using the spread operator in combination with the reduce function in JavaScript

I am attempting to generate all possible paths of the provided JSON object. I have managed to generate the paths, but I would like the final array to be flattened without any nested arrays inside it. I tried spreading the array, but there are still some ne ...

The Bootstrap navigation bar is experiencing functionality issues when viewed on Chrome mobile browsers

I'm currently testing out the bootstrap 3 navbar feature on my meteor application, but I'm encountering some issues specifically on mobile devices. The problem seems to be that the toggle button is not showing up as expected. Interestingly, it wo ...

How can VueJs effectively update the data fetched using the created function?

When working with the Promise Object, I prefer to utilize the "then" and "catch" functions instead of asynchronous functions for handling responses in a simpler way. This allows me to avoid using await and conditional if-else statements to check the stat ...

Is there a way to successfully transfer both the event and props together?

For simplifying my code, I created a function that triggers another desired function when the Enter key is pressed. Here's an example of how it works: const handleKeyDown = (event) => { if (event.key === 'Enter') { event.preventDefa ...

Troubleshooting problem with Angular's ng-repeat directive in dealing with varying number of child objects

I am currently dealing with tree-structured data where the parent nodes can have an indefinite number of children, and those children can also have an indefinite number of children, creating a deeply nested structure. While I have successfully formatted th ...

Sorting JSON data in EJS based on categories

Hello, I am facing a dilemma. I need to apply category filtering to a JSON file but I am unsure of how to proceed with it. For instance, I wish to filter the 'vida' category along with its description and price. I seem to be stuck at this junctu ...

What could be the reason my form inputs are not capturing any data?

I am currently working with React to build a form, but I am facing an issue. Whenever I try to type in the form fields, nothing seems to happen. Upon inspecting the state of each input in the React dev tools, I noticed that it is only capturing one letter ...

Run a PHP script that creates a PDF file using jQuery AJAX

I am currently working with a form that looks like this: <form action="tcpdf/examples/example_0611.php" method="get"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="subm ...

Error in GLSL file: "Module parsing error: Unexpected symbol"

I'm currently working on creating a custom image transition using a shader, and I require a fragment.glsl file for this purpose. However, when I try to import this file into my .js file, I encounter the following error: Compiled with problems: ERROR ...