The CSS underline stays stationary when clicked

I'm attempting to implement a sliding horizontal line that moves on click of hyperlinks. Check out the code at: http://codepen.io/anon/pen/JdEPPb

The HTML structure is as follows:

    * {
      box-sizing: border-box;
    }
    
    body {
      font: 300 100% 'Helvetica Neue', Helvetica, Arial;
    }
    
    .container {
      width: 50%;
      margin: 0 auto;
    }
    
    ul li {
      display: inline;
      text-align: center;
    }
    
    a {
      display: inline-block;
      width: 25%;
      padding: .75rem 0;
      text-decoration: none;
      color: #333;
    }
    
    .one:active ~ hr {
      margin-left: 0%;
    }
    .two:active ~ hr {
      margin-left: 25%;
    }
    
    .three:active ~ hr {
      margin-left: 50%;
    }
    
    .four:active ~ hr {
      margin-left: 75%;
    }
    
    hr {
      height: .25rem;
      width: 25%;
      margin: 0;
      background: tomato;
      border: none;
      transition: 0.3s ease-in-out;
    }
    <div class="container">
      <ul>
        <li class="one"><a href="#">Uno</a></li><!--
     --><li class="two"><a href="#">Dos</a></li><!--
     --><li class="three"><a href="#">Tres</a></li><!--
     --><li class="four"><a href="#">Quatro</a></li>
        <hr />
      </ul>
    </div>

No JavaScript code is used in this implementation.

Currently, when I click on Two, the underline doesn't move underneath it immediately. I have to hold the click for longer for it to move, and when I release the mouse button, it falls back to One.

Answer №1

:active is triggered only when the mouse button is held down on the element, indicating active clicking.

Alternatively, you can utilize :target instead of :active.

The CSS pseudo selector :target matches when the hash in the URL corresponds to the id of an element.

By assigning values to the href attribute of links and ids of li elements, we can use :target to target the specific li that has been clicked:

* {
  box-sizing: border-box;
}
body {
  font: 300 100% 'Helvetica Neue', Helvetica, Arial;
}
.container {
  width: 50%;
  margin: 0 auto;
}
ul li {
  display: inline;
  text-align: center;
}
a {
  display: inline-block;
  width: 25%;
  padding: .75rem 0;
  text-decoration: none;
  color: #333;
}
#uno:target ~ hr {
  margin-left: 0%;
}
#dos:target ~ hr {
  margin-left: 25%;
}
#tres:target ~ hr {
  margin-left: 50%;
}
#quatro:target ~ hr {
  margin-left: 75%;
}
hr {
  height: .25rem;
  width: 25%;
  margin: 0;
  background: tomato;
  border: none;
  transition: 0.3s ease-in-out;
}
<div class="container">
  <ul>
    <li class="one" id="uno"><a href="#uno">Uno</a></li><!--
 --><li class="two" id="dos"><a href="#dos">Dos</a></li><!--
 --><li class="three" id="tres"><a href="#tres">Tres</a></li><!--
 --><li class="four" id="quatro"><a href="#quatro">Quatro</a></li>
    <hr />
  </ul>
</div>

Answer №2

As you move your mouse, the element changes its position even when the mouse button is held down. The issue lies with the :active selector, which only applies styles while the element is actively being clicked.

To fix this, replace the :active selector with the class .active. Here's how you can do it:

.one.active ~ hr {
  margin-left: 0%;
}
.two.active ~ hr {
  margin-left: 25%;
}

.three.active ~ hr {
  margin-left: 50%;
}

.four.active ~ hr {
  margin-left: 75%;
}

Additionally, add some functionality to the elements:

var elems = document.querySelectorAll(".one,.two,.three,.four");
for (var i = 0; i < elems.length; i++) {
  elems[i].addEventListener("click",function(e){
    if(document.querySelector(".active")){
      document.querySelector(".active").classList.remove("active");
    }
    e.currentTarget.classList.add("active");
  });
} 

You can view a demo of this code on CodePen: http://codepen.io/vandervals/pen/wagwBQ

Answer №3

Here's a solution to ensure the active link is displayed when the menu is active. The issue with your current code is that you have used the : selector instead of the . selector. You'll also need to incorporate a bit of JavaScript for this to work correctly.

Check out this link for an example implementation.

Answer №4

Check out this JSFiddle link.

$('ul li').on('click', function() {
    $('li').removeClass('active')
    $(this).addClass('active')
})

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

Unable to apply margin right to React Material-UI table

I am struggling to add margin to the right of a mui table with no success. Below is the code I have used: <TableContainer> <Table sx={{ mr: 100 }} aria-label="customized table"> <TableHead> <Tabl ...

flexbox used to create a fixed sidebar on the left

I want to create a fixed left sidebar using flexbox. The sidebar should have its own scroll bar if the content is long, and I don't want it to move when I scroll down the main content. Check out this example for reference: http://codepen.io/tedartus ...

Troubleshooting problem with AngularJS ng-repeat

Seeking assistance with an angularjs issue as a newcomer to the platform. Building a photo gallery where the initial page displays thumbnail photos from twitter and instagram using ng-repeat loop. Hovering over an image fades it out, revealing a button f ...

What is the best way to incorporate a PHP file into an HTML file?

Below is the code snippet from my index.php: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Voting Page</title> <script type="text/javascript" src="js/jquer ...

JavaScript: Display all global variables on Internet Explorer

Is there a way to retrieve the instance name of my class without passing it as a parameter? I have tried looping through all global objects and comparing them with the this pointer. This method works in Chrome and Firefox, but not in Internet Explo ...

In JavaScript, it is necessary to determine if a checkbox is checked when modifying an input box

I have a table where each <td> contains an input box and a checkbox like this: <td> <input class="Comment" type="text" data-db="comment" data-id="{{uid}}"/> <input type="checkbox" id="summary" title="Check to set as Summary" / ...

Tips on customizing the selected icon color in Material-UI's BottomNavigationAction styling

I'm facing an issue with Material-UI styled components and could use some assistance. My goal is to create a BottomNavigation bar in React using Material-UI v5 where the selected option's icon displays in red (#f00) while the unselected icons sho ...

Since updating my background-image, the header images have mysteriously vanished

Currently, I am in the process of building a webpage and want to create a default navigation bar that will be consistent across all pages. Below is the code snippet from the file where I wish to include my navigation bar: <html> <head> < ...

Bootstrap struggles to create panels of uniform size

Here is the code snippet I am currently working with: <div class="col-md-4"> <div class="panel panel-default"> <div class="panel-heading"> <h4><i class="fa fa-fw fa-tasks"></i> Extreme Performance</ ...

Viewing the XML response generated by a JavaScript file (SOAP Request) on the IIS server

My current setup involves utilizing a calendar system with an API accessible via SOAP requests on an IIS server. Initially, my approach was to create an HTML page and use JavaScript to display the SOAP request response. However, the response did not retur ...

Ways to stop VoiceOver from selecting the background content when a modal is open

Is there a way to prevent VoiceOver from reading the content behind a modal? I tried using aria-modal=true, but it seems VoiceOver does not support this feature by default like NVDA and JAWS do. I found more information about this on . According to the in ...

Inline CSS for altering the appearance of text within a DIV container

Within the confines of this DIV element... <div name="layer1" style="background-color:lightblue;"> <hr>Site:Downtown DataCenter Device: 2KBS</hr> </div> Hello there, I am utilizing Inline CSS Styling. Is it possible to make the t ...

Difficulty enforcing mandatory checkboxes

Seeking assistance on making checkboxes required. I am creating a form using bootstrap 4 and validating it using the JS example from bootstrap documentation. I have added "novalidate" to the form, "required" to inputs, and included the following script: ...

Possible rewrite: "Unable to use jQuery to add elements to data fetched through AJAX requests."

I am looking to add a button to copy code inside every div that has a class starting with language. The code is functioning properly, however, after attempting to retrieve data from the database using Ajax, the button no longer appears in the div as it did ...

Use PHP and jQuery to convert HTML to JSON from a specified URL and generate a tree view of the HTML elements

When a URL is entered into a textbox and the "OK" button is clicked, the left side of the page displays a preview of the HTML while the right side shows a tree view of the HTML tags (body, header, div, span, etc.) as shown in the attached image. The expect ...

Update the styling of each div element within a designated list

Looking for a way to assist my colorblind friend, I am attempting to write a script. This is the layout of the page he is on: <div class="message-pane-wrapper candy-has-subject"> <ul class="message-pane"> <li><div style=" ...

Rotate images every 5 seconds, pulling them directly from the server

I am looking to update the users every seven seconds on my website. To do this, I need to retrieve all user information from the server using JavaScript. What is the most efficient way to accomplish this task? My initial thought is to send an HTTP request ...

What could be causing my submit button to fail to send form data? - Issues with HTML/Node

Currently, I have a straightforward form set up for individuals to sign up for a waiting list for my product. However, I'm encountering an issue where the form is not submitting. The application is running smoothly on localhost:3000. The page loads c ...

"How to change the hover background of a select element in Chrome from its default setting to something else

https://i.sstatic.net/G2deM.png Is there a way to remove the background color on hover and replace it with a different color? .drp-policydetails { border: 1px solid #dddddd; background-color: #ffffff; } <div className="form-group"> <sele ...

Which property within the <mat-option> element is used for toggling checkboxes on and off?

I'm experimenting with dynamically checking/unchecking a checkbox in mat-option. What attribute can I use for this? I've successfully done the same thing with mat-checkbox using [(ngModel)]. Here's the snippet of my code: app.component.html ...