K
K
Konstantin Teploukhov2018-05-23 04:17:26
JavaScript
Konstantin Teploukhov, 2018-05-23 04:17:26

1 condition works always and another only 1 time after page loading. Why?

Hello .

Just an apology.

Скажу сразу что обычно моим опыт рабаты с js заканчивается на подключение плагина . Поэтому возможно вопрос глуп и не обоснован .

I have a css class fixed-header which (oddly enough) fixes the header . The header needs to be fixed only if: The width of the screen / browser eye (or whatever is measured there) is more than 1200px Tb only on laptops + PC

Here is the code I sketched, but it seems to me that it ... in general, something is wrong with it. (as an example: if you leave only the condition that adds or removes the class, then it always works. If you first scroll and then return and so on a couple of times, then the condition constantly works. But if you change the size of the browser window after loading, then the condition checking the size of the body does not work . I hope I was able to explain -_-)
$(function(){
    	var widthBody = $("body").width();
    	if (widthBody >= 1200) {
      $(window).scroll(function(){
        var winTop = $(window).scrollTop();
        if(winTop >= 30){
          $("header").addClass("fixed-header");
        }else{
          $("header").removeClass("fixed-header");
        }
      });
    	}
    });

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
A person from Kazakhstan, 2018-05-23
@LenovoId

you need to set another condition, like this
$(window).on('resize', function(){ like this
and then write like this:
$(window).on('resize', function(){
if($( window).width() < 640){

and what should happen !
but it's better to write $(window).on('load resize', function(){
as this should work not only on window change but also on load here
is a demo : https://codepen.io/topicstarter/pen/aGxpjg

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question