Is there a way to have a span update its color upon clicking a link?

I have 4 Spans and I'm looking to create an interactive feature where clicking a link in a span changes the color of that span. Additionally, when another link in a different span is clicked, the color of that span changes while reverting the previously clicked span back to its original color. I know this might sound confusing, but please bear with me. Below is some JavaScript code I found from another user's question. I've tried modifying it to suit my needs without much success. As a beginner in JavaScript, any tips or assistance would be greatly appreciated. Thank you in advance!

<script>
$(document).ready(function() {
        $("#sec1").click(function() {
            $("#sec1").removeClass('active');
            $(this).addClass('active');
        });
    });
</script>
CSS:
#sec1 { height: 8vh; width:10%; text-align:center; position: fixed; top:9vh; left:0;  background: rgb(238,238,238); /* Old browsers */
background: #7d7e7d; /* Old browsers */
...
html:
<span id="sec1" class="box"><a href="" class="one""><p style="margin-top:2.5vh; font-size:1.25em;"><b>MOVIES</a></p></div>
<span id="sec2" class="box"><a href="" class="two""><p style="margin-top:2.5vh; font-size:1.25em"><b>MUSIC</b></p></a></div>
<span id="sec3" class="box" ><a href="" class="three""><p style="margin-top:2.5vh; font-size:1.25em"><b>RADIO</b></p></a></div>
<span id="sec4" class="box"><a href="" class="four"><p style="margin-top:2.5vh; font-size:1.25em"><b>COMICS</b></p></a></div>

Answer №1

Consider using the box class selector instead of IDs for a more streamlined HTML structure.

$(document).ready(function() {
  var $boxes = $(".box").click(function() {
    $boxes.removeClass('active');
    $(this).addClass('active');
  });
});
a {color: #ffffff; text-decoration:none; font-family:arial;}
.box {
  color: #ffffff;
  background: rgb(238, 238, 238);
  /* Old browsers */
  background: #7d7e7d;
  /* Old browsers */
  background: -moz-linear-gradient(top, #7d7e7d 0%, #0e0e0e 100%);
  /* FF3.6+ */
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #7d7e7d), color-stop(100%, #0e0e0e));
  /* Chrome,Safari4+ */
  background: -webkit-linear-gradient(top, #7d7e7d 0%, #0e0e0e 100%);
  /* Chrome10+,Safari5.1+ */
  background: -o-linear-gradient(top, #7d7e7d 0%, #0e0e0e 100%);
  /* Opera 11.10+ */
  background: -ms-linear-gradient(top, #7d7e7d 0%, #0e0e0e 100%);
  /* IE10+ */
  background: linear-gradient(top, #7d7e7d 0%, #0e0e0e 100%);
  /* W3C */
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#7d7e7d', endColorstr='#0e0e0e', GradientType=0);
  /* IE6-9 */
  ;
  display: inline-block;
  padding:10px 20px;
  white-space: nowrap;
}
.active  {
  background: #aaa;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span id="sec1" class="box">
  <a href="#" class="one"style="margin-top:2.5vh; font-size:1.25em;">
      MOVIES
  </a>
 </span>

<span id="sec2" class="box">
  <a href="#" class="two" style="margin-top:2.5vh; font-size:1.25em">
    MUSIC
  </a>
</span>

<span id="sec3" class="box" >
  <a href="#" class="three" style="margin-top:2.5vh; font-size:1.25em">
    RADIO
  </a>
</span>

<span id="sec4" class="box">
  <a href="#" class="four" style="margin-top:2.5vh; font-size:1.25em">
    COMICS
  </a>
</span>

Answer №2

Your posted markup has some issues that need fixing.

One problem is that you opened a span tag <span>, but then mistakenly closed it as a div </div>. It should be closed as a span instead. </span>:

<span id="sec1" class="box"><a href="" class="one"><p style="margin-top:2.5vh; font-size:1.25em;"><b>MOVIES</a></p></div>

Additionally, the href attributes should point to a hash to prevent page redirection.

(Replace all instances of href="" with href="#")

Here's a simple solution to achieve what you want. Although it includes repeated code (not DRY), it demonstrates the concept clearly. The JavaScript, CSS, and HTML have been simplified:

JavaScript

$(document).ready(function() {

  // click box 1
  $("#sec1").click(function() {
    $(this).addClass('active');
    $("#sec2").removeClass('active');
    $("#sec3").removeClass('active');
    $("#sec4").removeClass('active');
  });

  // click box 2
  $("#sec2").click(function() {
    $(this).addClass('active');
    $("#sec1").removeClass('active');
    $("#sec3").removeClass('active');
    $("#sec4").removeClass('active');
  });  

  // click box 3
  $("#sec3").click(function() {
    $(this).addClass('active');
    $("#sec1").removeClass('active');
    $("#sec2").removeClass('active');
    $("#sec4").removeClass('active');
  });  

  // click box 4
  $("#sec4").click(function() {
    $(this).addClass('active');
    $("#sec1").removeClass('active');
    $("#sec2").removeClass('active');
    $("#sec3").removeClass('active');
  });  

});

CSS

.box {
  text-align:center;
  top:9vh;
  left:0;
  background-color: #7d7e7d;
  display:inline;
  white-space:nowrap;
  overflow:hidden;
  margin: 3px;
  padding: 3px;
}

.active {
  background-color: green;
}

HTML

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>

<span id="sec1" class="box">
  <a href="#">
    MOVIES
  </a>
</span>

<span id="sec2" class="box">
  <a href="#">
    MUSIC
  </a>
</span>

<span id="sec3" class="box" >
  <a href="#">
    RADIO
  </a>
</span>

<span id="sec4" class="box">
  <a href="#">
    COMICS
  </a>
</div>

</body>
</html>

http://jsbin.com/riranefuri/edit?html,css,js,output

Answer №3

To easily switch classes in a group of span elements, remove the class from all spans and then add it to the one that is clicked on.

<script>
$(document).ready(function() {
        $("span.box").click(function() {
            $("span.box").removeClass('active');
            $(this).addClass('active');
        });
    });
</script>

If you want to navigate through different pages using anchor tags, make sure to assign the "active" class to the appropriate link using server-side programming rather than JavaScript.

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

Exploring the source of the "Unexpected token ;" issue in an Express-JS application

Working on a project with Parse and Express-JS, I encountered an issue when trying to display an EJS page. The error message Unexpected token ; appeared while running the command line parse develop MyApp in Terminal. Below is the full stack trace of the er ...

The target for CountUp is not defined in React.js and is either null or undefined

I'm experiencing an issue with React.js while using the CountUp library. I've tried everything I can think of, but so far, nothing has worked. I even created a state to check if the component is ready to render CountUp. I'm unsure whether t ...

I am having trouble retrieving the Post values that were sent using jQuery ajax

UPDATE: After removing 'index.php' with .htaccess, I encountered a newly discovered issue which I am now working on resolving. UPDATE: Issue resolved! Turns out the problem was in the Javascript code: url: "/login/". It needed a trailing slash t ...

My React component is experiencing issues with the Console.log functionality

Utilizing React for a component, I have incorporated a button that triggers a function 'myFunction' upon clicking, which essentially executes a console.log command. Despite compiling the code without any errors in both Visual Studio and the brow ...

What is the process for adding parameters to a Fetch GET request?

I have developed a basic Flask jsonify function that returns a JSON Object, although I am not certain if it qualifies as an API. @app.route('/searchData/<int:id>',methods=["GET"]) def searchData(id): return jsonify(searchData(id)) Curr ...

How can I programmatically close the Date/Time Picker in Material UI Library?

Is there a way to programmatically close the Date/Time Picker in Material UI Library? ...

Delicate seams break up the different sections of the webpage

I'm facing an issue with my website where thin lines are appearing between each section when previewed in Safari and Chrome, but not in Firefox (as shown in the images). I've checked the CSS code for each section in Dreamweaver, where the lines d ...

Trigger a JavaScript function on a body click, specifically targeting certain elements to be excluded

I have a dropdown menu within a div element. I've created a javascript function called HideDropdown() that hides the menu when any main link on the page is clicked, except for links within the dropdown menu itself: <script> function HideDropdow ...

What is the best way to begin an ordered list from the number 2 instead of 1, while ensuring W3C validity and compatibility with

Is it possible to start an ordered list from 2 instead of 1? I need the solution to be compatible with all browsers, including IE6, and ensure that the HTML and CSS are valid. ...

GWT 2.5.1 - How to Restrict the Amount of Items Displayed in a Dropdown Menu (ValueListBox)

Currently, I am utilizing a ValueListBox to showcase a range of values for users to choose from. The main issue I am encountering pertains to IE11 and its subpar behavior when interacting with the control: The dropdown list appears all over the place (in ...

Are cookies always included in client requests?

With every interaction between the server and browser, cookies are exchanged back and forth. However, what happens when an image is requested? <img src='myPic.jpg' /> Is the browser also sending cookies during this type of request? If i ...

How to eliminate rows with images in Exceljs

I created a worksheet with an image in each row. However, when I filter or remove a row, the image for that row stays visible. I tested this on versions v4.4.0 and v4.3.0 I attempted various methods of adding images, but none of them seemed to work. Initi ...

A step-by-step guide on transferring data from an HTML file to MongoDB using Python Flask

I am currently developing a web application that involves uploading multiple CSV files and transferring them to MongoDB. To build this application, I have utilized Python Flask. To test out different concepts for the application, I have created a sample f ...

Tips for increasing the size of Material-ui Rating icons

I am currently utilizing npm to develop a widget. I aim to utilize the material-ui Rating component and have successfully integrated it. However, when I embed the widget on a webpage, the html font-size is set at 62.5%, causing the component to appear too ...

The persistent state is not being saved correctly by Redux-Persist and is instead returning the initial

I have included redux-persist in my project, but for some reason it is not persisting the state as expected. Instead, I keep receiving the initial state whenever I reload the page. Below is the snippet of my root-reducer: import { combineReducers } from & ...

I wish to trigger the function when the button with the ID "add_city" is clicked instead of it being activated upon pressing the Enter key as it currently is

Is it possible to trigger the function by clicking a button with the id "add_city", rather than just pressing Enter? function createCity(stateId, newCity, event) { if(event.keyCode == 13 || $(this).attr('id') === 'add_city') { i ...

Accessing XML data using Cross-Domain AJAX

New to this! I'm currently working on a client script that requires reading an XML file from another domain. I attempted to utilize JSONP, and while I receive a 200 response, the client is unable to access the data returned for some unknown reason. Tw ...

Version 2: "In case of an empty input field, the submit button should be

After experimenting with two different codes on my websites, I encountered an issue. The first code looked like this: $(document).ready(function(){ $('.sendButton').attr('disabled', true); $('#message').keyup(function ...

Ways to style text using variables in SASS without using quotation marks

When working in SASS, I have created the following mixin: @mixin background_gradient($dir, $from, $to) { background: linear-gradient('to #{$dir}', $from, $to); // for IE10 } However, when viewing it in the browser, the output appears as: b ...

Leveraging PHP for parsing an HTML document

I am currently working on a PHP application that involves parsing HTML content. My goal is to extract a particular column from a table and store it in PHP variables. Below is the code I'm using: $dom = new domDocument; @$dom->loadHTML($html); $d ...