The HTML element <a> can have both a href attribute and a onclick attribute

I'm currently facing a challenge with my project - I am trying to create a submenu that includes all sub-pages within a single HTML file.

However, whenever I attempt to use both href and onclick, the functionality fails to work as intended.

The only workaround I've found is to change the href attribute to "#", but this then prevents the page from being accessed by other pages.

It's worth noting that altering the return value of the function doesn't seem to make a difference in this case.

Any help or suggestions would be greatly appreciated!

Below is the snippet of HTML code I am working with:

<script>
function show(shown, hidden, hidden2) {
  document.getElementById(shown).style.display='block';
  document.getElementById(hidden).style.display='none';
  document.getElementById(hidden2).style.display='none';
  return true;
}
</script>

<ul>                
<li><a href="../info/index.html" onclick="return show('Page1','Page2','ṕage3');">Objective</a></li>
<li><a href="../info/index.html" onclick="return show('Page2','Page1','ṕage3');">Board of Directors</a></li>
<li><a href="../info/index.html" onclick="return show('Page3','Page1','ṕage2');">Membership</a></li>
</ul>

<div id="Page1" style="display:none">
<a href="#" onclick="return show('Page2','Page1','ṕage3');">Board of Directors</a></br>
<a href="#" onclick="return show('Page3','Page1','ṕage2');">Membership</a>   </br>
<p>

text

</p>

</div></br>

<div id="Page2" style="display:none">
<a href="#" onclick="return show('Page1','Page2','ṕage3');">Objective</a>    </br>
<a href="#" onclick="return show('Page3','Page1','ṕage2');">Membership</a></br>
<p>

text

</div></br>
  <div id="Page3" style="display:none">
<a href="#" onclick="return show('Page1','Page2','ṕage3');">Objective</a>  </br>
<a href="#" onclick="return show('Page2','Page1','ṕage3');">Board of Directors</a></br>
    <p>
text
 </p>

</div></br>

Thank you for any assistance you can provide.

Answer №1

return false; won't solve the issue because a mistake occurs before reaching this line in the code.

Review your show function call: you are passing 'ṕage3' as the third argument, and then trying to access

document.getElementById(hidden2).style.display = ...
. However, there is no element with an id of "ṕage3".

Simply replace 'ṕage3' with 'Page3', and that should resolve the problem

Answer №2

To prevent the default behavior in your OnClick event, make sure to return false. In this case, when calling show in your onclick function, returning false is necessary instead of true.

<script>
function show(shown, hidden, hidden2) {
  document.getElementById(shown).style.display='block';
  document.getElementById(hidden).style.display='none';
  document.getElementById(hidden2).style.display='none';
  return false;
}
</script>

When the user clicks on the anchor tag, it triggers the onclick event first. If the onclick returns false, the process will stop there. However, if it returns true, the default action will proceed, leading to a change in the window location based on the href attribute value.

Answer №3

Ensure to prevent the default event handling in JavaScript by using event.preventDefault();

Answer №4

$("button").on("click", function()
{
  alert(1);
  return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<button id="btn">Click Here</button>

Avoid using onclick in modern coding practices.

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

"Encountering an error with ExpressJS where it cannot GET a file, preventing access to other folders' content

My goal is to set up a simple server using expressJS to retrieve data for my Angular application. However, I've encountered an error that says 'Cannot GET/'. This is the code snippet of the webserver I attempted to create: var express = re ...

What is the process for converting Flask request JSON data into a dictionary?

Struggling with integrating JQuery ajax methods and Flask, attempting to make an ajax call to retrieve a form. The JavaScript code I have written is: $.ajax({ type: 'POST', url: '/projects/dummyName', data: JSON.s ...

Creating a private variable to perform a select_sum query

I have defined private variables in my CodeIgniter code like this: private $table = 'phone'; private $column_order = array(null, 'name', 'price'); private $type = array('type'); private $battery_consumption = array ...

Tips for retrieving all JavaScript source links from a website URL during page download

Is there a way to determine if a website is using a specific online JavaScript source, such as fontawesome? Some sources may only become apparent once they are actually loaded, rather than being visible in the website's source HTML. I attempted to us ...

What is the functionality behind this unique SCSS mixin that combines flexbox and grid layouts?

Discover a SCSS mixin for creating flexbox/grid layouts HERE. Take a look at the complete mixin code below: @mixin grid-col( $col: null, $grid-columns: 12, $col-offset: null, $gutter: null, $condensed: false, ...

Is it possible to modify a variable within the readline function?

Can anyone help me figure out how to update the variable x within this function? const readline = require('readline'); const r1 = readline.createInterface({ input: process.stdin, terminal: false }); let x = 1; r1.on('line', fu ...

inquiry into the ArcGIS REST API endpoint

Looking for assistance in retrieving data from an ArcMap Rest EndPoint using the jQuery script below. However, the endpoint is returning no data. jQuery script: dojo.require("esri.map"); dojo.require("esri.dijit.OverviewMap"); dojo.require("dijit ...

How can I transfer a JavaScript value to PHP for storage in an SQL database?

<script> var latitudeVal = document.getElementById("latitude"); var longitudeVal = document.getElementById("longitude"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); ...

The error message "TypeError: addNewUser is not a function in React.js onSubmit

What could be causing the error message "TypeError: addNewUser is not a function"? The issue arises when I complete the form and click save, displaying the error that addNewUser is not defined as a function. The problem occurs within the following code ...

Are there any debugging tools specific to Internet Explorer for JavaScript?

I need a reliable JavaScript debugger for Internet Explorer. I have tried using Firebug Lite, but it doesn't seem as detailed as the original Firebug when it comes to displaying JavaScript errors. Does anyone know how to pinpoint JavaScript errors in ...

Leveraging the spread operator in cases where the value is null

Is there a more elegant solution for handling null values in the spread operator without using if-else statements? In this specific case, I only want to spread assignedStudents if it is not undefined. When attempting to do this without using if-else, I e ...

Restrict the PHP generated Json response to display only the top 5 results

I need to modify my search bar so that it only displays the top 5 related products after a search. public function getProducts() { if (request()->ajax()) { $search_term = request()->input('term', ''); $locatio ...

What is the best method for resizing an SVG according to the size of my website's window?

I am attempting to implement a scalable settings icon SVG file that adjusts based on the window width. My approach involved creating a JavaScript function that alters the element's dimensions according to the window size, but unfortunately, this metho ...

Trouble with launching Semantic UI modal

I have implemented a button using Semantic UI and set up a click event to open a modal when clicked, but nothing is happening. When I click on the link, there is no response. I'm unsure what the issue might be. Below is the code for the button: < ...

Discover the steps to download web page data using Objective-C while ensuring that JavaScript has finished executing

I attempted something similar: NSString *url = @"http://www.example.com"; NSURL *urlRequest = [NSURL URLWithString:url]; NSError *error = nil; NSString *htmlContent = [NSString stringWithContentsOfURL:urlrequest encoding:NSUTF8StringEncoding error:&e ...

Interfaces and Accessor Methods

Here is my code snippet: interface ICar { brand():string; brand(brand:string):void; } class Car implements ICar { private _brand: string; get brand():string { return this._brand; } set brand(brand:string) { this. ...

JavaScript resets the timer whenever the page is refreshed

Is there a way to maintain the timer in a quiz even after refreshing the page? <html><h1>Js Timer</h1> <div style="font-weight: bold;" id="quiz-time-left"></div> <script type="text/javascript"> var total_seconds = ...

Unable to assign a height of 100% to the tr element or a width of 100% to the

While inspecting the elements, I noticed the presence of <tbody>, within which <tr> is nested. The issue arises when the tbody element has 100% height and width as intended, but <tr> always falls short by 4 pixels in height even when styl ...

Transform current JSON data into formatted JSON format using JavaScript or TypeScript

I have a JSON structure that needs to be reformatted in order to meet the requirements of an external service. Although the current format is complex and cannot be altered, I need to modify it to match the desired output for the external service. Current ...

Error 404 encountered in JqGrid while trying to receive data from the controller

C# MVC4 I encountered the following error: GET http://BLAHBLAHBLAH/Address/AddressData/ [HTTP/1.1 404 Not Found 71ms] while debugging. Here is my JS definition: $(function () { var filter = $("#ClientId").val(); //Address Grid $("#tickets" ...