What is causing the onclick event to not function properly when called from an external .js file?

I've created a .js file that contains code for a photo album application. The file includes functions for changing images when buttons are clicked. However, when I interact with the buttons, the images do not change as expected.

The code in the .js file looks like this:

var dp = document.createElement("img");
function changeImage()
{

    var list = document.getElementById('optionlist');
    dp.src = list.options[list.selectedIndex].value;
        alert(dp.src);
}

function prevImage()
{
    var list = document.getElementById('optionlist');
        alert("Arrived at prev");
    if(list.selectedIndex == 0)
    {
        list.selectedIndex = list.options.length - 1;
    }
    else
    {
        list.selectedIndex--;
    }
    changeImage();
}

// Other button functions...

// HTML structure and element creation...

function start() {
    // Function to set up the image gallery and button functionalities

}

// End of code

The corresponding HTML code is shown below:

<html>
<head>
<title>Photo Album</title>
<style>
p, td {color:blue;font-family:verdana;font-size:8pt}
h1 {color:black;font-family:verdana;font-size:14pt}
</style>
<script type="text/javascript" src="PAScript.js" language="javascript"></script>
</head>
<body onLoad="start()" bgcolor="grey">
    <!-- Body content here -->
</body>
</html>

If anyone could provide assistance on how to resolve the button behavior issue in my application, I would greatly appreciate it. Thank you.

Best regards.

Answer №1

When assigning the onclick attribute using JavaScript, it should be set to a function reference rather than a string.

previous.onClick = "JavaScript:prevImage()";

This should be corrected to:

previous.onclick = prevImage;

Make sure to update your other assignments to adhere to this format. Additionally, remember that onclick should be all lower case and is case sensitive.

When it comes to registering event handlers, it is recommended to use the following approach:

For standards compliant browsers:

previous.addEventListener('click', prevImage, false);

For Internet Explorer:

previous.attachEvent('onclick', prevImage);

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

Having trouble turning off a multi-select drop down option

Hello, I'm a newcomer to AngularJs and facing an issue with disabling my multiselect dropdown under a specific condition. Initially, I attempted to disable the dropdown using the following code: document.getElementById("multidropdown").disabled = tr ...

Images in Chrome are shivering when animated at unconventional positions

I am attempting to create a masking animation that reveals an image from its center. The animation is working well, but I have encountered a problem in Chrome where the revealed content shakes. Here is an example on jsfiddle: http://jsfiddle.net/BaKTN/ I ...

Refreshing the page causes Material UI Button to revert to default styling

My question regarding the Material UI Button losing styling after a page refresh (link: Material UI Button loses Styling after page refresh) went unanswered, so I am reposting with a CodeSandbox included for reference: https://codesandbox.io/s/bold-resonan ...

Executing an AJAX request with a specific state in Node.js

Instead of rendering add.jade directly, I have chosen to enhance the user experience by making an AJAX call to the endpoint. This allows me to maintain the URL as localhost:3000/books, rather than localhost:3000/books/add which lacks navigation state for ...

How can I apply concatMap in Angular?

Can you please guide me on how to effectively utilize concatMap with getPrices() and getDetails()? export class HistoricalPricesComponent implements OnInit, OnDestroy { private unsubscribe$ = new Subject < void > (); infoTitle ...

JSON has encountered an unconventional string at position 41 that was not anticipated

Attempting to learn Javascript as a beginner, I am facing an error that is puzzling me: SyntaxError: /home/runner/myrepl/config.json: Unexpected string in JSON at position 41 Upon checking my index.js file, it seems correct at position 41 (at least I beli ...

Failure to trigger bind action in connector.php for elfinder, a Javascript file manager plugin

function log() { $data = array( 'folder_id' => 1, 'user_id' => 1 ); $this->Folder_model->share($data); } function access($attr, $path, $data, $volume) { return strpos(basename($path), '. ...

What could be causing the "Error - Only secure origins are permitted" message to appear for my service worker?

Whenever I attempt to implement a service worker on my progressive web application page, why does the browser console display this specific error message? ERROR "Uncaught (in promise) DOMException: Only secure origins are allowed JavaScript Code: ...

Retrieve information from every nested array and present it in sequential order

I need to extract the index of each element in a nested array structure. For example, I have an array with 5 subarrays, each containing multiple elements. My goal is to retrieve the first element from each subarray, then the second element, and so on. Her ...

How can I assign a reference to a List component using react-virtualized?

Could someone help me with referencing the scrollable List in react-virtualized using a ref? I'm having trouble as my ref keeps showing its current attribute as undefined. Any tips on how to properly use a ref with react-virtualized List? This is wha ...

JavaScript Delayed Redirection

I'm attempting to launch opera from the command line and have it redirect to a page after 30 seconds. Here's what I currently have: C:\Programme\Opera\opera.exe -newpage javascript:function%20func1(){window.location.href='htt ...

AngularJS tree grid component with customizable cell templates

I have been utilizing the tree-grid component in AngularJS from this link: Here is an example of it on Plunker: http://plnkr.co/edit/CQwY0sNh3jcLLc0vMP5D?p=preview In comparison to ng-grid, I am unable to define cellTemplate, but I do require the abilit ...

The function "toggleHeightAndOpacity" cannot be accessed on this object because it is not defined

I'm attempting to invoke a variable function name, a task I have successfully accomplished many times in the past using code similar to that found here. <script type="text/javascript"> $.fn.toggleHeightAndOpacity = function(show) { ...

How can you determine the class of an element that was clicked within an iframe?

Is it possible to retrieve the class of an element that is clicked within an iframe? Here is the HTML code: <input id="tag" type="text"> <iframe id="framer" src="SameDomainSamePort.html"></iframe> This is the JavaScript code: $(docum ...

Sending a single data point via Ajax on the client side

I am facing an issue with connecting frontend and backend systems. I want to send a single value (radio1Value) from a JavaScript function using jQuery AJAX upon clicking. Is the function structured correctly as I have written it? If yes, how should the R ...

Guide to including objects into your project without the need for babel through the use of CDN

I'm struggling with getting my Vue code to transpile properly due to some issues. I have resorted to loading Vue and other packages directly using CDN links, like this: <script src="https://cdnjs.cloudflare.com/ajax/libs/survey-vue/1.8.33/surv ...

Detecting incorrect serialized data entries based on data types

In the scenario where the type MyRequest specifies the requirement of the ID attribute, the function process is still capable of defining a variable of type MyRequest even in the absence of the ID attribute: export type MyRequest = { ID: string, ...

How to open a link in the URL bar of Safari on iOS using JavaScript

My goal is to open a link through the iOS Safari address or URL bar. After testing, I have found that in newer iOS versions, the address bar no longer executes javascript:alert("hi"); as it did before. Have any new methods been introduced, or h ...

When using props.onChange(e.target.value) in a textField component in Material UI, it unexpectedly returns an object instead of a value

function FormInput(props) { const classes = formInputStyles(); return ( <div> <TextField onChange={(e) => props.onChange(e.target.value)} InputProps={{ classes, disableUnderline: true }} {...pro ...

Handle errors originating from unsuccessful connections to a server named "Event" when using RxJS's fromEvent method

Using rxjs fromEvent to establish a connection with a named sse Event, I am looking to handle an Error in case of connection loss namedEvent() { try { const eventSource = new EventSource( 'adress' ); return fromEvent ...