Search code examples
jquerycssangularjsjqlite

Variable value is not being passed inside the function


I have function, that doesn't work properly for some reason. In my AngularJS app I need to manipulate CSS with jqLite.

Let's say there are two div's and first one has certain width.

<div class="primary-item"></div>
<div class="secondary-item"></div>

I want to set secondary item width to be the same as primary.

Everything goes fine till the point when function changes CSS. Looks like widthToSet value didn't pass there.

secondaryItem.css({width: + widthToSet + 'px', height: '100px'});

Please see the code in the snippet below.

function changeCss() {
    var masterItem = angular.element( document.querySelector( '.primary-item' ) );
    var widthToSet = angular.element( masterItem.prop('offsetWidth') );
    alert("width to set is" + widthToSet);
    var secondaryItem = angular.element( document.querySelector('.secondary-item') );
    secondaryItem.css({width: + widthToSet + 'px', height: '100px'}); /*width is not being set*/
    //secondaryItem.css({width: '300px', height: '100px'}); /*works fine*/
}

angular.element(document).ready(function () {
  changeCss();
});
.primary-item {border: 1px solid red; padding: 10px;}
.secondary-item {border: 1px solid green; padding: 10px;}
.primary-item, .secondary-item {float: left; clear: both; margin-bottom: 10px;}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<div class="primary-item">Some content here</div>
<div class="secondary-item"></div>

Thank you!


Solution

  • Thanks to @Hacketo for help.

    The problem was in declaration of widthToSet variable.

    function changeCss() {
        var masterItem = angular.element( document.querySelector( '.primary-item' ) );
        var widthToSet = masterItem.prop('offsetWidth');
        var secondaryItem = angular.element( document.querySelector('.secondary-item') );
        secondaryItem.css({width: + widthToSet + 'px', height: '100px'}); 
    }
    
    angular.element(document).ready(function () {
      changeCss();
    });
    .primary-item {border: 1px solid red; padding: 10px;}
    .secondary-item {border: 1px solid green;}
    .primary-item, .secondary-item {float: left; clear: both; margin-bottom: 10px;}
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
    <div class="primary-item">Some content here</div>
    <div class="secondary-item"></div>