0

I would just like my CSS Style to read a variable from Javascript and set the CSS "top" value accordingly. Example:

$topPosition = false;
?>
<script language='JavaScript' type='text/javascript'>
    function windowsHeightPixels() {
        windowsHeight = $(window).height()
        if (windowsHeight > 750) {
           topPosition = false;
           //set the $topPosition = false;
        }
        else {
            topPosition = true;
            //set the $topPosition = true;            
        }
    }
    windowsHeightPixels();
    alert ("Height is " + windowsHeight + " Top Position is " + topPosition); 
</script>

<style>
...
#fixedbutton {
    position: fixed;
    <?php if ($topPosition === false) : ?> top: 650px;
    <?php else : ?> top: 127px;</p>
    <?php endif; ?>
    ...
}
</style>
1

1 Answer 1

1

Edit: Refactored to check the window height on page load.

Here's a slightly different approach that you may wish to consider. It doesn't require a PHP variable. Judging by the sample code you provided I'm assuming that you're using jQuery.

<script>
    function windowHeightThreshold() {
        var heightThreshold = 750;
        return $(window).height() > heightThreshold;
    }
    function checkWindowHeight() {
        var targetElement = $('#fixedbutton');
        if (windowHeightThreshold()) {
            targetElement.addClass("windowHeightThreshold");
        } else {
            targetElement.removeClass("windowHeightThreshold");
        }
    }

    $(window).on("resize", function() {
        checkWindowHeight();
    });           
    $(document).ready(function() {
        checkWindowHeight();
    });
</script>

Then, for your CSS:

<style>
    #fixedbutton {
        position: fixed;
        top: 127px;
    }
    #fixedbutton.windowHeightThreshold {
        top: 650px;
    }
</style>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank for your answer - it is very close. When zooming the page it is put in the correct positions. Zoom at> 149% moves the fixed button. When I refresh the page it is reset to the default position, Always the same position no matter the zoom level.
Now works well. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.