Andrea Giachetto Andrea Giachetto - 1 year ago 36
Javascript Question

.css() function doesn't set any properties to any elements

I've got an issue with a jQuery function: .css()

This is my HTML code:

<div class="..." id="about">

This is my jQuery Code:

(function($, window, document) {

$(function() {

var viewportHeight = $(window).height();

$('#about').css( "margin-top" , viewportHeight );

}(window.jQuery, window, document));

I've tried every possible combinations but this isn't working in any way. I've tried every possible synthax of the .css() method with no result.
I've also tried to apply other properties in the .css() func, other method to the $('#about') object as the .click or .fadeOut() when DOM is ready, with no result.

My environment is a project built with Yeomann, Grunt & Angular.js. I'm worried that Angular interferes with the function I'm building, but it seems weird to me because the .click() method on other HTML elements is working (for instance i'm able to .addClass() to elements).

Somebody know this issue?


As for comments it's very likely that jquery can't get the element because the element doesnt exist in that specific moment.

You should use more Angular feature and less Jquery stuff as well. Anyway one solution can be found using ng-init

<div ng-controller="AboutController">
    <div class="..." id="about" ng-init="measure()">

and then inside AboutController or any controller that wraps your about element you can use any code you prefer, i'll use the plain JS version

(function () {
    'use strict';

        .module('app') //whatever module you're using
        .controller('AboutController', tcController);

        tcController.$inject = ['$scope', '$window'];
        /* @ngInject */
        function tcController($scope, $window) {

            $scope.measure = function() {
                var viewportHeight = $window.height();
                document.querySelector('#about').style.marginTop = viewportHeight + 'px';