javascript exchange the content when clicking on a hyperlink

I'm encountering a bit of a challenge with this task... My javascript skills are a bit rusty, and I can't seem to pinpoint what's going wrong.

My goal is to have a navbar that disappears when a user clicks on a small arrow, revealing a second arrow. When the user clicks on the second arrow, the navbar should reappear. The entire navbar is contained within one tag. Since the menu is quite long, I want to give users the option to toggle it on and off.

The javascript function in the head section looks like this:

<script type="text/javascript">
function collapseMenu()
{document.getElementById("navbar").innerHTML ='<td id=navbar2><a href="javascript:void(0)" onclick="collapseMenu('navbar2');"><img src="arrow.gif"></a></td>';
}</script>

The text on the page is as follows:

<div id='navbar'>
<td>
<a href="javascript:void(0)" onclick="collapseMenu('navbar');"><img src="arrow.gif"></a>
</td>
</div>

When I place the id in the div tag, the arrow displays upon clicking the link, but it doesn't remove the old html between the div tags. Using span instead of div or changing between single and double quotes didn't make a difference. If I move the id="navbar" to the td tag, the nav bar disappears but leaves the background color unchanged in the space left by the old td tag. Ideally, I'd like the area to go blank except for the tiny arrow. So my first question is why aren't the div and span tags working properly, or why does placing the id in the td tag affect the background color?

My second question involves how to specify innerHTML in text through a variable. It would be helpful not to have everything inside a function in the header.

Any ideas you have would be greatly appreciated!

Answer №1

Not familiar with jsfiddle, but the code below showcases the issue when placed in an .htm file. Thank you.

<html>
<head>
<script type="text/javascript">
function hideBar()
{document.getElementById("navbar").innerHTML ='<td>show navbar</td>';
}</script>
<script type="text/javascript">
function hideBar2()
{document.getElementById("navbar2").innerHTML ='<td>show navbar</td>';
}</script>
</head>
<body>
<table width=500>
id in td tag
<tr>
<td rowspan=3 bgcolor="yellow" id="navbar">
<a href="javascript:void(0)" onclick="hideBar('navbar');">hide 

menu</a><br>menu1<br>menu2<br>    <br>menu3<br>menu4
</td>
</tr>
<tr><td>lots of content here<br>more content<br>    <br>more content<br>more<br>blah<br>blah<br>    <       /td>
</tr>

</table>


<table width=500>
id in div tag
<tr>
<div id="navbar2">
<td rowspan=3 bgcolor="yellow">
<a href="javascript:void(0)" onclick="hideBar2('navbar2');">hide 

menu</a><br>menu1<br>menu2<br>menu3<br>menu4
</td></div>
</tr>
<tr><td>lots of content here<br>more content<br>more content     <br>more<br>blah<br>blah<br         ;blah</td>
</tr>

</table>
</body>
</html>

Answer №2

When following the step to expand the background image, it resulted in one line of movement being shown within the gif. If the gif is moved outside the div container, it disrupts the alignment of cells on the page. It's important to note that while tables are no longer recommended as best practice for website layout, restructuring the entire table structure of a site would be a significant and complex task.

 <html>
    <head>
        <script type="text/javascript">
            function toggleBar(obj) {
                var navbar = document.getElementById("navbar");
                if (navbar.style.display == "none") {
                    navbar.style.display = "";
                    obj.innerHTML = "<img src='images/collapse.gif' alt='Hide Menu'>";
                } else {
                    navbar.style.display = "none";
                    obj.innerHTML = "<img src='images/expand.gif' alt='Show Menu'>";
                }
            }
        </script>
    </head>
    <body>
    <table style="width:100%;"><tr><td valign="top" style="width:20%;">
        <div style="background-color:lightgrey;text-align:left;padding-left:4px;width:80px;">
            <a href="javascript:void(0)" onclick="toggleBar(this);"><img src="images/collapse.gif" 

    alt="Hide Menu"></a>
            <div id="navbar">menu1<br>menu2<br>menu3<br>menu4</div>
        </div>
    </td><td valign="top" style="width:80%;"><table><tr style="background-color:blue;"><td><font 

    color="white">Title</font></td></tr>
    <tr><td>Body Text</td></tr></table>
    </td></tr></table>
    </body>

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

Creating an Array module in Node JS

Adding a prototype to the Array class can be done in native javascript with the following code: var myArray = Array; myArray.prototype.myMethod = function(){} var testArray = new myArray(); testArray.contains(); Now I need to achieve this using a nod ...

Retrieve the text content of a datalist option by accessing the label with jQuery

Utilizing data from a Json, I am populating a data-list in html. The options are added to the data-list with both value and label text. Upon clicking an option, I aim to insert both the value and text into a form text field. While accessing the option&apo ...

The functionality of the MVC jQuery grid is currently malfunctioning

Recently, I attempted to integrate a jQuery grid plugin from gijgo.com into my MVC application. Following the instructions provided on c-sharpcorner and/or codeproject meticulously, however, upon running the application, I encountered a troubling JavaScrip ...

Problem with exporting default class in Babel/Jest conflict

Currently, I am facing a challenge while testing the code using jest. The issue seems to be related to babel, especially regarding the export of a default class. Here is an example of the code causing the problem... export default class Test { get() { ...

What is the reason for Cloud Firestore's realtime database fetching all items?

Currently, I am developing a project with vuejs and I am facing an issue where I need to fetch only the last created item from Firestore's realtime database. However, when I execute the following code snippet, it retrieves all items from the database ...

Class component proceeding without waiting for function completion

My function, getactivity(), pulls and sorts data from an API and returns the sorted data in answer1 format. However, I am facing a problem where whenever I run the function to retrieve the data, it keeps returning nothing. Here is the full code: import Re ...

What is the method for determining the data type of a column in an Excel sheet that has been

Currently, I am utilizing the XLSX npm library to convert an Excel sheet into JSON format. However, all of the retrieved data is currently being returned as strings. To see a demo of the XLSX read process, you can visit this Stackblitz demo Is there a w ...

Challenge with JavaScript personalized library

No matter how many times I review my code, I find myself perplexed. Despite my efforts to create a custom library of functions from scratch (shoutout to stackoverflow for guiding me on that), the results are leaving me puzzled. A javascript file is suppose ...

Error in NodeJS when trying to run ESM: "ReferenceError: exports is not defined

Having a tough time with this task. I'm attempting to execute ESM scripts on Node 14 (AWS Lambda) I am working on running this piece of code to convert 3D objects to THREE JSON. This involves using the command node -r esm fbx2three.js model.fbx. I ...

Enhance your Vue PWA by utilizing ServiceWorker to efficiently cache remote media assets fetched from an array of URLs

In my PWA development project, I am looking to provide users with the option to download and cache all media assets used in the application. However, the default behavior of PWAs only caches assets when they are requested during app navigation. My goal is ...

The JavaScript variable assigned from the MySQL query through an Express API is returning as undefined, indicating that the promise is not resolving to

Hey there, I'm trying to assign the result of a MYSQL query to a JS variable so that I can use it multiple times. However, whenever I try to do this, I end up receiving an empty array. Can anyone point out what might be causing this issue in my code? ...

Disable checkboxes upon page initialization

I am working with a form that includes checkboxes. Whenever the page loads, clicking on the checkboxes automatically checks them. However, I am looking for a solution where the checkboxes are disabled or not clickable during the page load process. Once th ...

Which is Better for Creating DropDown Menus: CSS or JavaScript?

Starting a new project that involves dropdown menus with categories and subcategories within them. I'm curious about the advantages of using CSS3 only menus compared to traditional JavaScript ones. There are several jQuery menu options available as we ...

Using JavaScript (without jQuery), take away the CSS class from an element

Seeking assistance from experts on the process of removing a class from an element solely using JavaScript. Kindly refrain from suggesting solutions involving jQuery as I am unable to utilize it, and have little knowledge about its functionalities. ...

Is there a way to direct Webpack in a Next.JS application to resolve a particular dependency from an external directory?

Is it possible to make all react imports in the given directory structure resolve to react-b? |__node_modules | |__react-a | |__app-a | |__component-a | |__next-app | |__react-b | |__component-b // component-a import { useEffect } from ' ...

Marionette's Take on the Undead: Zombie Perspectives

Error in JS Console: Uncaught ViewDestroyedError: View (cid: "view351") has already been destroyed and cannot be used. backbone.marionette.js?body=1:1715 Code Snippet: initialize: (options) -> HWAs = @model.get('homework_assignments') @ ...

Switching hamburger menu icons in Vue.js

I am trying to change a hamburger menu icon in my header to a cross icon when it is clicked. I have created a function in the computed property of my Vue template, but I'm not entirely sure about the implementation. How can I achieve this? Below is t ...

Tips for managing Material-ui's <Autocomplete/> component based on the option's id

When dealing with HTML select in React, it's common to use an id or key to keep track of the selected value: <select value={value} onChange={(event) => setValue(event.target.value)}> {options.map((option) => ( <option value={optio ...

upright scrolling mouse slider

In my project, I have implemented a vertical slider with mousewheel control using SwiperJS from https://swiperjs.com/. Although the slider is working perfectly fine, I am looking to fix the positions while scrolling on the page similar to the example pro ...

Click the button to save the text to your clipboard with a customized

Can anyone suggest a method for duplicating div text using JavaScript while preserving the style attributes (italics, font family, size, etc.)? My goal is to paste the copied text into Word and have it maintain the same appearance as on the webpage. For e ...