At the ready stance for a particular grade of students attending a class

I have created a page with a navigation menu that can be scrolled using the wheel mouse. My goal is to ensure that the li item with the 'selected' class is always positioned in the first position on the left.

Is there a way to achieve this using jquery code?

$(document).ready(function() {
  var scrolling_size = 0;
  $("li").each(function(index) {
    scrolling_size += parseInt($(this).css("width"));
  });
  $("#menu").css("width", scrolling_size);
  scrolling_size = scrolling_size - parseInt($('#container').css("width"));

  $('#menu').bind('mousewheel', function(e) {
    $("#before").text("Left of the #menu Before scrollong: " + parseInt($(this).css("left")));
    if (e.originalEvent.wheelDelta > 0) {
      if (parseInt($(this).css("left")) <= -50) {
        $(this).css("left", "+=50");
      }
    } else {
      if (parseInt($(this).css("left")) >= -scrolling_size) {
        $(this).css("left", "-=50");
      }
    }
  });
});
#l,
#r {
  float: left;
  font-size: 80px;
}

#container {
  float: left;
  border: 1px solid green;
  width: 500px;
  padding: 2px;
  overflow: hidden;
  position: relative;
}

#menu {
  border: 1px solid blue;
  padding: 2px;
  position: relative;
}

ul {
  list-style-type: none;
  white-space: nowrap;
  overflow-x: visible;
  margin: 0;
  padding: 0;
}

li {
  border: 1px solid red;
  display: inline-block;
  font-size: 80px;
}

.selected {
  background: #0095ff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <div id="menu">
    <ul>
      <li>Hi !</li>
      <li>Text here</li>
      <li>Something like this</li>
      <li class="selected">Always</li>
      <li>Thanks !</li>
      <li>Bye</li>
    </ul>
  </div>
</div>

Here's an image for reference: image

I attempted this:

$("#menu").css("left", $(".selected").css("left"));

Unfortunately, it did not work. Any assistance would be greatly appreciated.

Answer №1

Here is a helpful code snippet for achieving a specific behavior:

$(document).ready(function() {

$("#menu ul li.selected").prependTo("#menu ul");

  var scrolling_size = 0;
  $("li").each(function(index) {
    scrolling_size += parseInt($(this).css("width"));
  });
  $("#menu").css("width", scrolling_size);
  scrolling_size = scrolling_size - parseInt($('#container').css("width"));

  $('#menu').bind('mousewheel', function(e) {
    $("#before").text("Left of the #menu Before scrollong: " + parseInt($(this).css("left")));
    if (e.originalEvent.wheelDelta > 0) {
      if (parseInt($(this).css("left")) <= -50) {
        $(this).css("left", "+=50");
      }
    } else {
      if (parseInt($(this).css("left")) >= -scrolling_size) {
        $(this).css("left", "-=50");
      }
    }
  });
});
#l,
#r {
  float: left;
  font-size: 80px;
}

#container {
  float: left;
  border: 1px solid green;
  width: 500px;
  padding: 2px;
  overflow: hidden;
  position: relative;
}

#menu {
  border: 1px solid blue;
  padding: 2px;
  position: relative;
}

ul {
  list-style-type: none;
  white-space: nowrap;
  overflow-x: visible;
  margin: 0;
  padding: 0;
}

li {
  border: 1px solid red;
  display: inline-block;
  font-size: 80px;
}

.selected {
  background: #0095ff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <div id="menu">
    <ul>
      <li>Hi !</li>
      <li>Text here</li>
      <li>Something like this</li>
      <li class="selected">Always</li>
      <li>Thanks !</li>
      <li>Bye</li>
    </ul>
  </div>
</div>

Answer №2

After some searching, I have discovered the solution: Here is the code snippet that needs to be included:

let currentPosition = $("li.selected").position();
$("#menu").css("left", currentPosition);

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

Variables for HTML comment form using PHP mail

How do I properly pass HTML form variables to a PHP mailer? The PHP code is: $comment = $_POST['comment']; $email = $_POST['email']; $to = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="60131313 ...

What is the best way to send pg-promise's result back to the controller in Express?

While working with Ruby on Rails (RoR), I am familiar with the MVC (Model-View-Controller) concept. In this framework, the controller is responsible for receiving data from the model, processing it, and rendering the view. An example of this structure look ...

URL to section of website without the navigation bar portion

I am trying to solve a problem with creating a link that will take me to a specific part of the page while taking into account the height of the navbar. The issue is that since the navbar is fixed to the top with a solid color, it ends up covering part of ...

Retrieve data from dropdown menu to showcase table using Node.js

I'm currently diving into learning nodejs and mongodb. My backend setup includes expressjs and mongojs, while ejs is handling the frontend of my application. The main goal is to allow users to select a class from a dropdown menu and view a correspondi ...

Using jQuery to Toggle the Height of Multiple Sections with a Single Function

I've got three different sections, each with varying heights and a simple structure like this: <section> <h2>My heading</h2> </section> What I want is for these sections to display at first, but then shrink dow ...

Align the list at the center within a div container

Struggling to align my image gallery within a designated div. Currently facing an issue where the icons appear too small and not perfectly centered. This is the CSS and HTML I currently have: <div id="social"> <ul> ...

I'm having an issue with Internet Explorer where the link doesn't function properly when I enclose the content within an <a> tag. Could anyone

I understand that this might not be the preferred approach, but a customer has requested live text wrapped in just one HTML tag.... Here's the challenge I'm facing: I currently have some code structured like this: <a href="google.com"> ...

Minimizing the frequency of getElementById calls for the same HTML element

When dealing with repetitive function calls using the same element as a parameter, is it more effective to store the element as a global variable? For instance, imagine a function that is triggered on every key press and takes an element as an argument. ...

Exploring a utility function for saving object information in a dynamic state

Imagine my state was structured like this: state = { customer: { name: { elementType: "input", elementConfig: { type: "text", placeholder: "Your Name" }, value: "" }, street: { e ...

Issues with div and hyperlinks/forms

I am currently working on creating a left sidebar in my HTML code, but I am still new to this. In the div for the sidebar, I have three buttons. However, Weebly keeps notifying me of an issue with the <a> tag, and the second button's link appear ...

Incorporate the Bootstrap classes to arrange the divs side by side, ensuring that any surplus space is utilized effectively

Having implemented a layout with two images and two paragraphs side by side, everything seemed to be working fine until I encountered an issue when setting both images' height to 400px. The goal was for the paragraph to adjust its size based on conten ...

Utilizing HTML5's geolocation API to construct a geofence

Is there a way to utilize the HTML5 geolocation API to determine if a user is located in a specific area? I'm considering setting a central latitude and longitude and creating a radius around it, so the site will function as long as the user is within ...

Leveraging PHP to dynamically insert image file names into a directory for populating the HTML img src attribute in a Bootstrap

I am trying to dynamically populate a Bootstrap carousel with images from a folder by using PHP to scan the image files. However, instead of displaying the images in the carousel, only the names of the images are being listed. Below is my code, and I have ...

Using Conditions in a Javascript For Loop

I would like to utilize a for loop to achieve the following task. Within an array, I have a predefined set of values representing hex colors for a chart. My goal is to extract a specified number of those values using the loop with two options. If the ...

Perform queries securely using AJAX when the document is fully loaded

Hello everyone, I'm facing an issue with the custom statistics feature on my website. I collect user data (similar to Google Analytics) and store it in tables for a few months. However, these tables have become too large and are causing slow page loa ...

URL encoding an AJAX POST request is being done by Microsoft Edge

I have encountered an issue with my $.ajax call where it is being encoded with URL encoding, but only in Microsoft Edge. Chrome and Firefox are working perfectly fine without any problems. Below is the Ajax call I am using: var promise = $.ajax({ url: ...

Tips for uploading a file using Axios in a form

When uploading a file to a Flask server, I can access files from the flask request global by using raw HTML with the following code: <form id="uploadForm" action='upload_file' role="form" method="post" enctype=multipart/form-data> < ...

The jQuery UI dialog box is malfunctioning and failing to return a value when the user clicks a button

I have a jQuery UI dialog box that I want to use for confirming a deletion action with the user. The issue I am facing is that the code below seems to return "True" or "False" immediately when the dialog pops up, even before the user has clicked the "Yes" ...

Using the `preventDefault` method within an `onclick` function nested inside another `onclick

I am currently working on an example in react.js <Card onClick="(e)=>{e.preventDefault(); goPage()}"> <Card.body> <Media> <img width={64} height={64} className="mr-3" ...

How come my data cannot be displayed using ajax?

Here is the code snippet: var xml=new String(""); //function to send data every 5 seconds window.setInterval(function() { //code to obtain xml file alert(xml);// when I try alert my variable xml contain data ...