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

Discovering the type in Typescript by specifying a function parameter to an Interface

Consider this sample interface: interface MyInterface { x: AnotherThing; y: AnotherThingElse; } Suppose we make the following call: const obj: MyInterface = { x: {...}, y: {...}, } const fetchValue = (property: keyof MyInterface) => { ...

Changing the size of the Modal Panel in Ui Bootstrap for a customized look

Currently, I am in the process of developing an application that utilizes Ui bootstrap to seamlessly integrate various Bootstrap components with AngularJs. One of the key features I require is a modal panel, however, I found that the default size option &a ...

Detecting when the Ctrl key is pressed while the mouse is hovering over an element in React

In my project, I have implemented a simple Grid that allows users to drag and drop items. The functionality I am trying to achieve is detecting when the mouse is positioned on the draggable icon and the user presses the Ctrl key. When this happens, I want ...

Retrieving Hyperlinks from JavaScript Object for Integration with D3-Created Table

Issue: I'm facing a problem where the HTML link extracted from an Associative Array is treated as a string instead of being applied as a clickable link in the browser. For a detailed visual example and code snippet, visit: http://example.com/code Da ...

Share content on Facebook using a single-page application

This inquiry may not be specifically tied to a particular software stack, framework, or coding language. In the current project I'm working on, we are utilizing AngularJS for developing the front-end with a static landing page that loads real data an ...

Sending data as arguments in URL fetch requests with JavaScript

Hey there, I've been experimenting with making a GET request in React. In the past, with jQuery, I used to do something like this: $.get("Run",{ pr: "takeData", name: "Bob"}, function (o) { console.log(o) ...

Serve as a proxy for several hosts with identical URL structures

I've been utilizing the http-proxy-middleware to handle my API calls. Is there a way to proxy multiple target hosts? I've searched for solutions in the issues but still haven't found a clear answer. https://github.com/chimurai/http-proxy-m ...

Designing a personalized carousel component in Angular

Looking to replicate this design, any tips? I'm aiming for a carousel layout with developers listed in a project, where the center item is larger than the others. Any guidance on how to achieve this look? ...

Pass the ID of a dynamic textbox element to a child window upon clicking a link

One of the challenges I'm facing involves a textbox labeled "Branch Code" that links a branch to a corporate card transaction. At times, there is a requirement to split a transaction among multiple branches. To facilitate this process, I am constructi ...

BASH-SHELL SCRIPT: Display a specific portion of content from a file

Recently, I stumbled upon a text file containing a snippet of HTML code: >>nano wynik.txt which includes the following text: 1743: < a href="/currencies/lisk/#markets" class="price" data-usd="24.6933" data-btc= "0.00146882" My goal is to extr ...

How to trigger a JavaScript function using a button click

I've been struggling to figure out why my JavaScript code isn't functioning properly within Ionic. Can anyone guide me on how to store a number in a variable, display that variable, and increment it when a button is clicked? I have successfully ...

Delving into the World of ES6 Symbols

Throughout my experience with various programming languages, from C# to Lisp to Scala to Haskell, symbols have consistently behaved as singleton objects. This means that any two symbols with the same name are guaranteed to be identical. In Racket: (equal? ...

Implementing an API route to access a file located within the app directory in Next.js

Struggling with Nextjs has been a challenge for me. Even the most basic tasks seem to elude me. One specific issue I encountered is with an API call that should return 'Logged in' if 'Me' is entered, and display a message from mydata.tx ...

What is the reason in AngularJS for requiring directive attributes to be hyphen-separated while their scope variables are camelCased?

Here is an example in Html: <!-- Note 'display-when' is hyphenated --> <wait-cursor display-when="true"></wait-cursor> Then, when defining it in the directive: scope: { // Note 'displayWhen' is camelCased show: ...

Interactive ASP.NET MVC4 Dialog Box for Input Text

Currently, I am in the process of developing a complex web application with multiple sections that require users to input comments. I am searching for an efficient method to create a partial view that can display a modal dialog for adding comments and then ...

Bringing the Jquery cursor into focus following the addition of an emoji

Looking to add emojis in a contenteditable div but facing an issue with the cursor placement. Here is a DEMO created on codepen.io. The demo includes a tree emoji example where clicking on the emoji adds it to the #text contenteditable div. However, after ...

What is the reason behind re-rendering pages specifically for error messages in express and nodejs?

In the world of web development, it is commonly accepted practice to re-render a page to display error messages and redirect to show success messages. While implementing this principle in my code using express js, I have encountered a few challenges. For ...

Ensure that the dimensions of a div remain consistent across all screen resolutions, specifically for desktops and not mobile devices

Currently I am in the process of creating a highly secure and encrypted social network, but I have hit a stumbling block. I hadn't considered how my website would display on other desktops and laptops (not mobile devices). The issue is that I set all ...

Using SWIFT on iOS to perform a JSON query

Is there a way to convert this query into Swift? <script> jQuery.ajax( { url: "http://website.net/api/Clients/", type: 'POST', headers: {"Token": "Votre token"}, dataType: "json", data: { "PhoneNumber": phoneNumberValue ...

Turkish text is not appearing correctly on the UIWebview when embedded in HTML

One of the challenges I encountered in my iOS project involved programming a UIWebView to load content in both English and Turkish from a web service. To accomplish this, I formatted the HTML string with the necessary headers and saved it locally before pr ...