Apply absolute position style with JavaScript / jQuery

I am creating a right-aligned site.

The last menu item drops out of the page because it is in absolute order to the left of the parent.

I am trying to create a solution for my menu below.

jsfiddle - http://jsfiddle.net/ashconnolly/6gjVr/

I cannot hardcode the pos left -xx style because the width of the last menu item will be different (due to the text inside it), so my use is js. I almost hacked it, but I just need to apply the variable as the position of an absolute left style only on hover. There may be a better css solution, but I could not find it.

Any help is appreciated !: D

Edit: Updated explanation.

+4
source share
3 answers

You have already calculated the left from your last menu, why didn’t you use it?

$(document).ready(function () {
var menuitemwidth = document.getElementById("last-menu-item").offsetWidth;
var menuitemdropdownwidth = document.getElementById("last-menu-item-drop-down").offsetWidth;
//alert(menuitemwidth);
var leftval = menuitemdropdownwidth - menuitemwidth;
//alert(leftval);
    $("#last-menu-item").mouseenter(function(){
        $("#last-menu-item-drop-down").css({'position':'absolute','left':'-'+leftval+'px','display':'block'});
    });
    $("#last-menu-item").mouseleave(function(){
        $("#last-menu-item-drop-down").css({'display':'none'});
    });

});

Check here

+1
source

As you probably already know, this is a bad practice to "print" javascript values ​​using the framework. It will become indispensable pretty soon.

But you can separate (element) logic from a view (element), i.e. print / format html elements in their templates, setting data-attributelike this in your html:

<ul id="last-menu-item-drop-down" data-pos="left" data-val="-133px">

Then change your javascript to:

// cache last element, no need to jquery search on every hover
var last_elem = $("#last-menu-item-drop-down");

// set position and alignment
last_elem.css('position','absolute').css(last_elem.data("pos"), last_elem.data("val"));

// set dropdown meny visibility to hidden (do it by css)
last_elem.hide()

// show/hide
// ...

You can also do offset calculations in javascript and only specify position in your templates

Fiddle at: http://jsfiddle.net/cYsp6/7/

+1
source

css

$("#last-menu-item").mouseenter(function(){
var a=-(parseInt($("#last-menu-item-drop-down").css('width'))-parseInt($("#last-menu-item").css('width')));
 $("#last-menu-item-drop-down").css('position','absolute').css('left',a);
 $("#last-menu-item-drop-down").show();
});
$("#last-menu-item").mouseleave(function(){
   $("#last-menu-item-drop-down").hide();
});

:

Fiddle

0

Source: https://habr.com/ru/post/1545815/


All Articles