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

The Access-Control-Allow-Origin error is preventing the Angularjs post request from going through

I am encountering an issue with my index.html file that is sending a post request to localhost:3000/SetUser. The error I keep receiving states XMLHttpRequest cannot load https://localhost:3000/SetUser. No 'Access-Control-Allow-Origin' header is p ...

Multiplication cannot be performed on operands of type 'NoneType'

Hello everyone, I am attempting to calculate the unit price and quantity from this table using the following model: class Marketers(models.Model): category =models.ForeignKey(Category, on_delete=models.CASCADE, null=True) name =models.CharField(max ...

Transform the snake code by incorporating a visual image as the face of the serpent

Can someone help me change the snake's face to an image instead of a color fill in this code? And how can I add arrows for mobile compatibility? (function() { // Insert JS code here })(); // Insert CSS code here This code snippet includes functi ...

Why won't my AngularJS checkbox stay checked?

In my application, I have the following code: <input type="checkbox" ng-checked="vm.eduToEdit.test" /> {{vm.eduToEdit.test}} <input type="checkbox" ng-model="vm.eduToEdit.test"> The value of vm.eduToEdit.test is displaying t ...

Is it possible to integrate payment methods such as PayPal or Stripe in Vue.js without using a server like Express? If so, how can I implement this

After completing the development of my web shop in Vue.js, I realized that the payment method is still missing. I am wondering if I need to integrate Express in order to process payments through Stripe? Currently, I do not have a server like Express set up ...

Exporting Javascript functions is not possible

Programming in TypeScript import { Component, OnInit } from '@angular/core'; import {loadCalendar} from '../../../../scripts/artist/artist-home'; import {activate_searchBar} from '../../../../scripts/search_bar_activate'; @C ...

I consistently encounter the error message 'XRWebGLLayer is not defined no-undef' while implementing three.js within react.js to develop a WebXR application

Trying to implement WebXR with Three.js in a React project, encountering the error: 'XRWebGLLayer' is not defined no-undef for baseLayer: new XRWebGLLayer(session, gl) The code works fine in vanilla JavaScript but fails to compile in React. ...

Display or conceal toggle in ruby utilizing jQuery

I'm facing an issue with the functionality of a button that is meant to hide and show a form using jQuery. Initially, I added a path to signup in the button so that it would display and function properly. Now, when I click the button, the form shows u ...

Implementing a function trigger on button click using jQuery

I recently created a jQuery code snippet: <span id="counter-up" class="timer"> </span> <div class="buttons"> <button id="trigger">Find out!</button> </div> </div> <div class="container"> </div> & ...

Disabling the past dates on a date picker based on the selected date from another date picker

Is it possible to disable past dates in the End Date picker based on the selected date in the Start Date picker? For example: If I choose 20th November 2019 as the Start Date, I want to prevent selection of any past dates in the End Date picker. <ht ...

Issue with submitting VueJS form on mobile devices, works fine on web browsers but not on

I have encountered a similar problem before, but I haven't found a suitable solution yet. In my VueJS application, the submit function works perfectly fine on desktop browsers like Chrome and Firefox, but for some reason it refuses to submit on mobil ...

Having numerous bxsliders implemented in a Genesis child theme

I'm currently working on incorporating multiple bxsliders through custom fields in a wp genesis child theme. The initial slider was successfully implemented using the following function within the genesis child theme functions: add_action('genes ...

Does it follow standard practice for Array.filter to have the capability to also perform mapping on an array of objects?

While experimenting with Array.filter, I made an interesting discovery. By forgetting to include an equality check, my array was unexpectedly mapped instead of filtered. Here is the code snippet that led to this result: const x = [{ name: 'user' ...

Encountering an issue when attempting to construct the project: it asks for callback functions, but instead received an [

I'm currently facing an issue while trying to access a function that is crucial for updating some database values. Whenever I attempt to build the project, I encounter the following error: Error: Route.post() requires callback functions but got a [ ...

utilize the flex index.html layout

Upon reviewing the template, I noticed that there is code implemented to check if the client has the necessary version. This code performs certain actions based on whether or not the required version is available. Additionally, there seems to be an <obj ...

The lightbox fails to display in IE when a synchronous ajax request is triggered

I have a piece of code that displays a lightbox with the message 'Please Wait', followed by a synchronous ajax request that removes the lightbox once it's completed. This setup works perfectly in most browsers, but in Internet Explorer, the ...

Conceal and reveal elements using v-if

Check out my fiddle: DEMO creating a new Vue instance: { el: '#app', data: { modules: ['abc', 'def'] } } I am looking for a way to hide or show elements using v-if based on the values in an array called modules[]. ...

checkbox appear based on vue condition

I have checkboxes on my list that are always checked, but I only want them to be checked if the associated object's property "include" is set to true. Currently, all the checkboxes are checked by default, and when I click on them, they uncheck and ex ...

Failed to make a request to https://registry.npmjs.org/node-modules because of an error: error:0906D06C:PEM routines:PEM_read_bio:no start line

Encountering an issue while attempting to install a JS package. Despite conducting thorough research, I have not been able to resolve the error. Please help me identify where I am going wrong. npm ERR! request to https://registry.npmjs.org/node-modules ...

What is the best way to update information in a mongoose document using the _id field?

Although it may sound like a typical question, I've already conducted research and couldn't find a solution. I'm currently working on developing a discord bot and I don't have much experience in this area. The issue I keep encountering ...