Leveraging em units in jQuery Script

I'm currently in the process of building a website and I'm facing an issue with converting measurements to em's. The script that I have reused from a previous project only seems to work with pixels, despite my efforts to make it compatible with em's.

$(window).scroll(function(){
    $("#nav").css("top",Math.max(0,96-$(this).scrollTop()));
});

To see the current behavior in action, check out this demo:

http://jsfiddle.net/hwRSF/1/

If anyone is able to provide guidance on how to resolve this issue, I would greatly appreciate it!

Answer №1

If you're working with the scrollTop() function, remember that it returns values in pixels. To use these values effectively, you'll need to convert them into em units based on your base font size.

Assuming your base font size is 16, a simple way to convert pixel values to em units is by dividing the pixel value by 16.

Here's a snippet of navigation CSS code using em units:

#nav {
 ...
 top: 6em; /* 96 / 16 = 6*/
 ...
}

Using jQuery, you can dynamically adjust the top position of an element based on the scroll position. Here's an example using the scrollTop() function:

$('#nav').css("top", Math.max(0, (96 - $(this).scrollTop()) / 16) + "em");

For a live example, check out this fiddle: http://jsfiddle.net/hwRSF/3/

Answer №2

Using 'em' for positioning at the top is perfectly acceptable:

$("#nav").css("top", '3em');

I've had no issues with this approach while using Chrome 28 on my Linux Mint system.

Answer №3

One clever approach is to allow the browser to render 1em and then use javascript to determine its value.

HTML

<div class="hidden dummy-em"></div>

CSS

/* If you don't want the user to see it, use hidden
   You can use any element with a height of 1em
   Avoid using display: none; */

.hidden{
    position: absolute;
    left: 500vw;
}
.dummy-em{
    height: 1em;
}

Javascript(jQuery)

// JavaScript returns values like these in pixels
var oneEm = $('.dummy-em').innerHeight();

Save yourself from doing the calculations and let the browser handle it for you

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

Guide on determining the total count based on a specific condition with the help of jQuery

Using AJAX, I have successfully retrieved all status values such as Active, ACTIVE_DRAFT, and Pending. However, I only want to select the statuses that are equal to ACTIVE. To do this, I am using an if condition which is working fine. After filtering by st ...

Display a button in a single row table

Here is my table markup: <table class="table table-condensed"> <thead> <tr> <th>id</th> <th>task</th> <th>date</th> </tr> </thead> ...

The method of displaying the date is determined by the starting date

I have a pair of datepickers and I want the to date to be based on the selected from date. The to date should always be one day after the selected from date, ensuring they are not the same. For example: If I select 'from' 07/18/2018, the ' ...

Using Node.js to create a RESTful API that pulls information from MongoDB

I am currently working on creating a REST API using Node.js to retrieve the last N rows from a MongoDB collection. Here is my current code snippet: var express = require("express"); var app = express(); var bodyParser = require("body-pa ...

Filling form fields with array data (AngularJS)

Although I'm new to AngularJS, I'm struggling to figure out how to handle a list of arrays returned from the searchAll function. console 0: {mobile: "12345678", lastname: "last01", firstname: "first01"} 1: {mobile: "87654321", lastname: ...

What is the best way to include a variable or literal as a value in styled components?

When it comes to managing various use cases, I always rely on props. However, I am currently facing a challenge in changing the border color of a styled input during its focus state. Is there a way to utilize props for this specific scenario? Despite my f ...

Is there a way to attach an event listener to a span that was inserted using DTColumnBuilder?

I am attempting to include an onclick event for a span element that is generated by DTColumnBuilder. DTColumnBuilder .newColumn('Invoice') .withTitle('<span class="li-table-head ...

Unable to retrieve the JSON response item

Currently, I am in the process of setting up an AJAX call with the intention of manipulating the response data. Upon inspecting my browser's network console, this is the response I am seeing: { "message": "success", "file": "dump.xml" } Thi ...

Ways to transfer a button click event to a callback function

Fiddle: http://jsfiddle.net/cmw0s2rk/ function HandleTopNavClick($elem, pretext = "", replace = false, e) { debugger; e.preventDefault(); var href = $elem.href; } $("ul.check-it li a").on("click", HandleTopNavClick($(this), "clickhere_", true, even ...

How can I restrict the selection of only one checkbox within an iframe window?

Here is my JavaScript snippet: var iframe = document.getElementById('pltc'); iframe.contentWindow.document.open('text/htmlreplace'); iframe.contentWindow.document.write('<input type="checkbox" name="tc0">Yes<input type="c ...

Identifying functions that contain dots in their names using JSHint

While running jshint on a JavaScript file, I encountered functions with dots in their names for namespacing purposes. Specifically, within the d3 library, there is a significant portion of code that resembles: d3.select("something") Should I simply disab ...

JavaScript Lint Warning: Avoid declaring functions inside a loop - unfortunately, there is no way to bypass this issue

In my React JS code snippet, I am attempting to search for a value within an object called 'categories' and then add the corresponding key-value pair into a new map named sortedCategories. var categoriesToSort = []; //categoriesToSort contains ...

JavaScript click or text-to-speech

Currently, I am working on a web application that is designed to automatically read text. Below is the code snippet that I am using: function hablalo() { var palabra = new SpeechSynthesisUtterance('Casilla 6 turno E18'); palab ...

retrieve the responseText in an ajax request

I am looking to receive Ajax feedback. var response = $.ajax({ url : 'linkAPI', type : 'get', dataType: 'JSON' }); console.log(response); Only the respo ...

Swiper - tips for managing navigation visibility based on screen size in React

I have implemented a React Typescript swiper slider styled with tailwind CSS. The slider functions correctly, but I am facing an issue when trying to hide and show the navigation buttons on different breakpoints. Initially, I use the 'hidden' cla ...

Display or conceal toggle in ruby utilizing jQuery

I'm facing an issue with the functionality of a button that is meant to hide and show a form using jQuery. Initially, I added a path to signup in the button so that it would display and function properly. Now, when I click the button, the form shows u ...

Utilize AJAX and JavaScript to retrieve file information and facilitate file downloads

I have developed a script that intercepts Captcha form submissions. Typically, when the form is submitted, a file will be downloaded (such as exe or zip) in the usual way where it appears at the bottom of the Chrome browser and gets stored in the "download ...

challenges with website design on Internet Explorer 7

Welcome! This is my HTML code: <div style="width:220px;float:left;" id="radio_text"> <ul style="width:20px;float:left;display:block;"> <li style="list-style:none;line-height:13px;height:13px;float:left;"><input type="radio ...

Choosing a root element in a hierarchy without affecting the chosen style of a child

I am working on a MUI TreeView component that includes Categories as parents and Articles as children. Whenever I select a child item, it gets styled with a "selected" status. However, when I click on a parent item, the previously selected child loses its ...

JavaScript: The variable `scopes` is declared

I'm completely new to JavaScript. Can anyone help me understand why this code isn't working, and what changes I need to make to fix it? function getResults(keywords) { foo.foo = function() { var bar = foo.getSomeText; // ...