-2

I'm iterating through a list of li's to get the li which is in the center of the screen (on scroll) with this function:

var findMiddleElement = (function(docElm){
    var viewportHeight = docElm.clientHeight,
    elements = $('li');

    return function(e){
        var middleElement;
        if( e && e.type == 'resize' )
        viewportHeight = docElm.clientHeight;

        elements.each(function(){
            var pos = this.getBoundingClientRect().top;
            // if an element is more or less in the middle of the viewport
            if( pos > viewportHeight/2.5 && pos < viewportHeight/1.5 ){
                middleElement = this;
                return false; // stop iteration 
            }
        });

        console.log(middleElement);

    }
})(document.documentElement);

This works great so far. The Problem is that 'middleElement' will return something like this:

<li style="padding-top: 12.8438px; padding-bottom: 12.8438px;">Menu Item 8</li>

I need to add a CSS style to it. Since middleElement.css doesn't work, I need a way to get the selector of the found element.

Cœur
  • 37,241
  • 25
  • 195
  • 267
sparks
  • 79
  • 2
  • 7

1 Answers1

2

The property is called "style" in pure JavaScript.

For example:

middleElement.style.color = "red";

With jQuery (probably less performant):

$(middleElement).css({color:"red"})
grilly
  • 450
  • 4
  • 11
  • 1
    please don't add styles to elements without really good reason's. Especially when you could `middleElement.addClass('theClass');` – Nathan Koop Jun 03 '16 at 13:23
  • @NathanKoop Is this a convention ? This is the first time I hear about this – tektiv Jun 03 '16 at 13:25
  • 2
    @tektiv: read this questions: http://stackoverflow.com/questions/2612483/whats-so-bad-about-in-line-css setting the style with javascript is basically the same -- but good to use for dynamically calculated values. (so my example is a bit bad it that sense...) – grilly Jun 03 '16 at 13:27
  • 1
    @tektiv there are a number of good reasons in the link. Basically using inline CSS is hard to maintain (always needing to update every page where it's used), if you've got one (or a few) CSS files, they're cached on the browser after the first request so following requests are smaller (and faster). In this specific instance, the user is already using jQuery which has an `addClass` method to do it "properly" (https://api.jquery.com/addclass/) – Nathan Koop Jun 03 '16 at 13:36
  • 1
    @NathanKoop Well I knew about the inline CSS issue .. But I didn't make the link between both ^^' Thank you anyway ! – tektiv Jun 03 '16 at 13:38