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

What is the standard way to write the server-side code for HTTP request and response handling?

I stumbled upon these resources: How to send HTTP request GET/POST in Java and How to SEND HTTP request in JAVA While I understand the client-side aspect, how can this implementation be done on the server side? The goal is to utilize the link on the clie ...

Encountering an unexpected token ';' in a random generator while attempting to utilize an if-else statement for determining DOM manipulation

After dabbling in programming on and off for a few years, I've finally decided to dive deep with some simple personal projects. One of the tasks I'm working on is creating a randomizer for a pen and paper RPG, where it samples from an array at ra ...

Tips for automatically setting focus to the following cell after inserting a new row in AngularJS

Transitioning from the Knockout world to Angular, I am facing an issue with a key-press event for tab. Whenever I add a new row in the table, the focus shifts to the information icon in the URI bar instead of the next cell in the newly created row. I belie ...

Error messages arising from JSON files generated by PHP

My current setup involves using a PHP script to generate a cache of JSON files. We utilize a PHP file on our server to interact with a large database, fetching result sets in JSON format for use with jQuery and other frameworks on our site. The core scrip ...

JavaScript - Receiving alert - AC_RunActiveContent.js needed for this page to function

When I attempt to open the HTML file in my application, a pop-up message appears stating that "This page requires AC_RunActiveContent.js." However, I have already imported and referenced the AC_RunActiveContent.js file in my package. Can someone assist m ...

Experiencing unexpected output from Angular model class method

I have developed a user-friendly Invoicing & Inventory management application that showcases a list of invoices for each customer. However, there seems to be an issue with the calculation of the Grand Total function, which I am struggling to rectify due to ...

The surprising behavior of Rails rendering partials even when they are commented out has

I'm intrigued by how Rails 5 handles partials and if there might be a hidden problem I haven't encountered yet. On my current page, I have two partials - one that is included in the HTML itself, and another that is supposed to render inside an aj ...

Can you identify this numerical category?

Can you identify this number type? console.log(0100); // output 64 console.log(050); // output 40 console.log(010); // output 8 In a hexadecimal system, it would be: 0100 = 256 050 = 80 010 = 16 ...

Guide on setting a session variable upon clicking an <a> hyperlink

Having this issue where I need to set a session variable when clicking on a regular link like: <a href="home" name="home">home</a> From my research, it seems PHP cannot capture the click event in order to set a session variable. I've he ...

Why do style assignments lose their motion when executed right after being made?

If you take a look at this specific fiddle in Webkit, you will see exactly what I am referring to. Is there a way to define the style of an element when it is first specified, and then its final state? I would like to be able to fully define a single-ste ...

Tips on uploading information from a PDF document onto a website

My goal is to develop a program or script that can extract data from PDF form fields and automatically input it into the corresponding textfields on my website, all done through the front end. The problem I'm facing is not knowing where to begin with ...

Tips on saving Firebase Storage image url in Firebase database?

How do I store the URL of an image uploaded to Firebase Storage in Firebase Database? When executing the code below, I encounter the following error: Uncaught (in promise) FirebaseError: Function DocumentReference.set() called with invalid data. Unsuppor ...

Font that has been downloaded is not showing up on the HTML document

I recently downloaded a new font and ensured the file location is correct, but for some reason it's not working: <style> @font-face { font-family:"myfont"; src: url('fonts/Helvetica85Heavy_22449.ttf'); } h1 { font-family: ...

Is there a way to bring to life the addClass() and removeClass() jQuery functions through animation?

I am currently developing a website and I want to be able to toggle the visibility of sections by using the ".hidden" bootstrap class within click events. Here is the basic code snippet: $('selector').click(function(){ $('*part-to-hi ...

Navigate through an overflowing element in react/next

I have a component with a fixed width and overflow-x-auto. I want to hide the scroll bar and replace it with arrow buttons for scrolling left and right. How can I add this functionality to my component? Here is the code for my component: <div className ...

The jQuery ajaxError() function triggers if the user navigates away from the page before it has fully loaded

We have implemented a global ajaxError() handler using jQuery to notify users of any AJAX failures: $(document).ajaxError(function() { $("There was a network or server error. Please try again later.").dialog({ title: "Error", mod ...

Tips for leveraging stage 3 functionalities in TypeScript?

Array.prototype.at() is currently in the proposal stage 3. Even after adding "lib": ["ESNext"] to my tsconfig.json, I encountered the error: Property 'at' does not exist on type 'number[]'. Could you shed some light ...

Utilizing Jquery to implement active state and unique IDs during mouseover operation

I found this great example on Stack Overflow that demonstrates Jquery Show/Hide functionality when hovering over links. It works perfectly by showing the content of the next div when the corresponding link is hovered over. However, I'm facing an issu ...

The CSS "mask" property is experiencing compatibility issues on Google Chrome

Hey there! I've recently developed a unique progress bar component in React that showcases a stunning gradient background. This effect is achieved by utilizing the CSS mask property. While everything runs smoothly on Firefox, I'm facing a slight ...

Basic looping through a single item to showcase its properties and data

I have an object that looks like this: const people = { men: 4, women: 2, total: 6, participants: { 1: 4, 2: 1, 3: 0 } }; I am looking to display the following result: 1 participants count 4 2 participants count 1 3 participan ...