Switch the background image with a single click

How can I change the background image of my horizontal menu when a user clicks on a link? Here is the code I have been working with:

<div class="grid_16" id="menu">
  <ul id='menuTab' class='sqglDropMenu'>
      <li><a href='Home' onclick='changeIt();'>Home</a></li>
      <li><a href='profile' onclick='changeIt();'>Profile</a></li>
      <li><a href='products' onclick='changeIt();'>Products</a></li>
      <li><a href='samples' onclick='changeIt();'>Samples</a></li>
      <li><a href='contact' onclick='changeIt();'>Contact</a></li>
  </ul>
</div>

Here is my JavaScript function:

function changeIt(){    
  document.getElementById('menuTab').style.backgroundImage = "url(../images/tab_off.png)";
}

This is the CSS where the initial background image is set:

.sqglDropMenu li {float: left; list-style: none; text-align:left; margin-left:5px; position: relative; display: block; line-height: 30px;}
.sqglDropMenu li a {display: block; white-space: nowrap; float: left; text-align:center; font-size: 1.3em; color: #fff;  font-weight:bold; padding-top:5px; margin-top:-1px; background:url(../images/menu_tab.png) no-repeat; width:182px; height:58px;}
.sqglDropMenu li ul {float:left; position: absolute; visibility: hidden; z-index:1000; margin: 0; margin-top:50px; * margin-top: 0px; clear:both; margin-left:-475px; background:url(../images/menuback.png) no-repeat; width:944px; height:60px}
.sqglDropMenu li ul li{float: left; position: relative; clear: left; border-width:0px; display: inline; margin: 0;}
.sqglDropMenu li ul li a{margin-left:20px; border-width:0px; text-align:left; font: 9pt Arial; adding:5px 12px; z-index:100; width: 100px; background:none;}
.sqglDropMenu li ul li a:hover{border-width:0px; background:none;}

Any assistance would be greatly appreciated. Thank you, Stephen

Answer №1

Once the link is clicked, you will be directed to the specified page rendering your function redundant. However, there are alternative solutions:

  1. Utilize PHP to retrieve the current page and adjust the anchor class accordingly to achieve your desired background effect.
  2. Alternatively, use JavaScript in a similar manner as PHP. Here's an example:

var path = window.location.pathname; var page = path.substring(path.lastIndexOf('/') + 1); if (page == 'currentpage.html'){ document.write('CurrentPage') } else { document.write('CurrentPage') }

I trust this information proves helpful to you.

Answer №2

Give this code a shot

<script type="text/javascript>
$('a').on('click',function(e){
    var hrefArr = this.href.split('=img='));
    e.preventDefault();
    switch(hrefArr[2]){
    case 'Home':
      img = 'smith.jpg';
      break;
    case 'About':
      img = 'jones.jpg';
      break;
   } 
   $('body').css({backgroundImage:'url(images/'+img+')'});
});

Answer №3

When you click the link, your browser will automatically redirect to the URL specified in the href attribute. To prevent this redirection and instead change it using JavaScript, use the function changeIt(); return false in the onclick handlers.

Answer №4

To enhance the appearance, consider adjusting the background attribute:

function customizeTab() {
  document.getElementById('menuTab').style.background = "url(../images/tab_off.png)";
}

The issue might be caused by the <li> elements obstructing the background visibility. Have you tried embedding this style directly into the stylesheet to observe any changes?

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 iterating through an array of objects in Vue?

Having trouble looping through an array of objects in Vue3 <template> <div class="shadow-xl w-96 h-96 md:h-[600px] md:w-[600px] lg:my-12 lg:w-[700px] lg:h-[700px] rounded-md" > <button @click="getData">Get ...

tag assistance for incorporating an attribute without a value

Trying to create: <div data-dropdown-content class="f-dropdown content"> using the tag helper. It seems there is no specific syntax for attributes without values <%= tag(:div, :class => "f-dropdown content", data: {dropdown-content: ""}, :& ...

Jasmine: Methods for verifying if the accurate URL is invoked during a GET request

I need to test a service function, but I'm unsure how to mock an internal service function that is called within the main function. My goal is to verify if the correct URL is being accessed. Below is the code snippet for my service: angular.module(" ...

Truncating decimal points in JavaScript

In this scenario, if the number after the decimal point is 0, then the zero should be removed. Otherwise, the number should be displayed as it is. Here are some examples of what I am aiming for in vue: 100.023 => 100.023 1230.0 => 1230 ...

Image Positioned Outside Border in HTML

I'm working on creating a personalized homepage for my browser and I want to display 3 images with captions evenly spaced within a divider. Although everything seems to be in place, the border of the outermost divider is not covering the images. How c ...

Is it necessary to encode the content before transmitting HTML in JSON from the server to the client?

When it comes to sending HTML content from the server to the client for displaying user comments in a rich JS app that communicates through a JSON API, there are some considerations to keep in mind. One important question is how to handle the content with ...

InertiaJS retains form data following validation errors

Within my InertiaJS/VueJS project, I have a prop that receives data from the backend: event: { type: Object, default: () => { return {} } }, This is how the event object looks in the backend: ['name' => 'Event Name'] To m ...

Element child's attribute value not properly implementing Polymer's two-way data binding

I have a product-card custom element with the following structure: <dom-module id="product-card"> <template> <div class="card-main-content layout horizontal center"> <content select="img"></content> < ...

Attempting to emulate the grid showcase using flexbox styling

Creating this layout using CSS Grid was a breeze. However, I wonder if it can be achieved with Flexbox. What do you think? .Message { display: inline-grid; grid-template-areas: ". name""date text"; } .Date { align-items: ...

Adjusting the thickness of the CSS cursor line upon entering an input field

Having an image as the background for an input field has been causing issues for me. Although I can adjust the line-height and font-size easily, the cursor line appears outside of the background image when clicking inside the input field. Is there a speci ...

The width of my search bar keeps shifting every time I click on the navbar button

Whenever I switch between the home and about page buttons in the app's navbar, the width of my search bar changes. Why is this happening? (This issue occurs only on desktop). Here is my code: https://github.com/StrikerOne65/snewz ...

Using include() function causes conflict with Bootstrap functionality in PHP

Here is the HTML code I'm trying to use with my index.php file, but I'm encountering an issue. <!-- nav bar --> <nav id="top"> <nav class="navbar navbar-xs navbar-custom"> <div class="container-fluid" > <di ...

Troubleshooting: AngularJS - Issues with nested controllers not functioning properly within ng-include

According to the AngularJS documentation (refer to nested controller fragment), I am attempting to implement nested controllers using ng-include Main.html <body id="spaWrapperApp" ng-app="spaWrapperApp"> <div class="container-fluid" id=" ...

Testing for expressjs 4 using Mocha revealed unexpected behavior when attempting to spy on a function called within a promise. Despite setting up the

I have encountered a situation with some test cases structured like this: it('does stuff', function(done) { somePromise.then(function () { expect(someSpy).to.have.been.called done() }) }) When the assertion in a test case fails, it ...

struggling with AJAX loading issues on a jQuery webpage

I have been utilizing the jquery load function to load a page into a div, and while the loading part itself works perfectly fine, I'm experiencing an issue. Here's the basic code snippet: $("div#loadhere").load("newfile.html?" + new Date().getTi ...

The designated <input type=“text” maxlength=“4”> field must not include commas or periods when determining the character limit

In the input field, there are numbers and special characters like commas and dots. When calculating the maxLength of the field, I want to ignore special characters. I do not want to restrict special characters. The expected output should be: 1,234 (Total ...

angular table disabled based on condition

I have a table in my HTML file and I am trying to figure out how to disable the onClick function if the start date is greater than the current date. <ng-container matColumnDef="d"> <th mat-header-cell ...

What is the correct timing for implementing a JavaScript delay to activate CSS styling?

Let's say I have some CSS like #joe { transition: opacity 500ms; opacity: 0; } Next, I include JavaScript that triggers the addition of a div and then animates the opacity to = 1 when you click the page. document.body.onclick = function () { var j ...

JavaScript recursive function to find the sum of array elements that equals to the given target number n

Currently, I am making my way through the Javascript course available on freecodecamp. However, in one of the lessons that cover recursive functions, I have hit a bit of a roadblock. The code snippet that is causing me confusion is as follows: function su ...

Toggle button based on text input to activate or deactivate

I need help with a script that will enable a button only when all required input fields are filled and a checkbox is checked. Currently, the button is being enabled even if only the last input field is filled. Can anyone assist? js $(document).ready(func ...