Div Boven aan pagina houden

Status
Niet open voor verdere reacties.

joppieb

Gebruiker
Lid geworden
1 apr 2014
Berichten
22
Hallo,

Wat ik graag wil maken is volgende:

Zodra iemand naar onder doet scrollen, dat er een bepaalde class of id word vast gezet aan de bovenkant.
en dat de rest eronder door scrollt
Wie kan mij hier verder mee helpen ?

Gr Jop
 
Dat klopt,

Het gaat hierom een zoekbalk. Die zoekbalk staat normaal iets naar beneden zeg ongeveer 150px van de top.
Als mensen dan omlaag gaan scrollen verdwijnt normaal de zoekbalk als je meer dan 150px gaat scrollen.
Nu zou ik graag willen dat zodra hij langs die 150px gaat hij zich vastklinkt aan de bovenkant van het scherm.
 
hier heb ik een kleine voorbeeld voor je
Code:
if(window.scrollY > 150) {
zoekdiv.style.position = fixed;
zoekdiv.style.top = 0;
 
}
 
Ben al stuk wijzer :)
Heb op mijn pc een test bestand gemaakt wat werkt. Alleen zodra ik hem op de main site zet waar nog andere javascriptcodes staan krijgt hij een conflict, en doet de site niets meer.
Hoe krijg je nu 2 verschillende code aan t werken op 1 pagina?
 
Heb nu het volgende in een file staan:

Code:
(function($) {
  var defaults = {
      topSpacing: 0,
      bottomSpacing: 0,
      className: 'is-sticky',
      wrapperClassName: 'sticky-wrapper',
      center: false,
      getWidthFrom: ''
    },
    $window = $(window),
    $document = $(document),
    sticked = [],
    windowHeight = $window.height(),
    scroller = function() {
      var scrollTop = $window.scrollTop(),
        documentHeight = $document.height(),
        dwh = documentHeight - windowHeight,
        extra = (scrollTop > dwh) ? dwh - scrollTop : 0;

      for (var i = 0; i < sticked.length; i++) {
        var s = sticked[i],
          elementTop = s.stickyWrapper.offset().top,
          etse = elementTop - s.topSpacing - extra;

        if (scrollTop <= etse) {
          if (s.currentTop !== null) {
            s.stickyElement
              .css('position', '')
              .css('top', '');
            s.stickyElement.parent().removeClass(s.className);
            s.currentTop = null;
          }
        }
        else {
          var newTop = documentHeight - s.stickyElement.outerHeight()
            - s.topSpacing - s.bottomSpacing - scrollTop - extra;
          if (newTop < 0) {
            newTop = newTop + s.topSpacing;
          } else {
            newTop = s.topSpacing;
          }
          if (s.currentTop != newTop) {
            s.stickyElement
              .css('position', 'fixed')
              .css('top', newTop);

            if (typeof s.getWidthFrom !== 'undefined') {
              s.stickyElement.css('width', $(s.getWidthFrom).width());
            }

            s.stickyElement.parent().addClass(s.className);
            s.currentTop = newTop;
          }
        }
      }
    },
    resizer = function() {
      windowHeight = $window.height();
    },
    methods = {
      init: function(options) {
        var o = $.extend(defaults, options);
        return this.each(function() {
          var stickyElement = $(this);

          var stickyId = stickyElement.attr('id');
          var wrapper = $('<div></div>')
            .attr('id', stickyId + '-sticky-wrapper')
            .addClass(o.wrapperClassName);
          stickyElement.wrapAll(wrapper);

          if (o.center) {
            stickyElement.parent().css({width:stickyElement.outerWidth(),marginLeft:"auto",marginRight:"auto"});
          }

          if (stickyElement.css("float") == "right") {
            stickyElement.css({"float":"none"}).parent().css({"float":"right"});
          }

          var stickyWrapper = stickyElement.parent();
          stickyWrapper.css('height', stickyElement.outerHeight());
          sticked.push({
            topSpacing: o.topSpacing,
            bottomSpacing: o.bottomSpacing,
            stickyElement: stickyElement,
            currentTop: null,
            stickyWrapper: stickyWrapper,
            className: o.className,
            getWidthFrom: o.getWidthFrom
          });
        });
      },
      update: scroller,
      unstick: function(options) {
        return this.each(function() {
          var unstickyElement = $(this);

          removeIdx = -1;
          for (var i = 0; i < sticked.length; i++) 
          {
            if (sticked[i].stickyElement.get(0) == unstickyElement.get(0))
            {
                removeIdx = i;
            }
          }
          if(removeIdx != -1)
          {
            sticked.splice(removeIdx,1);
            unstickyElement.unwrap();
            unstickyElement.removeAttr('style');
          }
        });
      }
    };

  // should be more efficient than using $window.scroll(scroller) and $window.resize(resizer):
  if (window.addEventListener) {
    window.addEventListener('scroll', scroller, false);
    window.addEventListener('resize', resizer, false);
  } else if (window.attachEvent) {
    window.attachEvent('onscroll', scroller);
    window.attachEvent('onresize', resizer);
  }

  $.fn.sticky = function(method) {
    if (methods[method]) {
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error('Method ' + method + ' does not exist on jQuery.sticky');
    }
  };

  $.fn.unstick = function(method) {
    if (methods[method]) {
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method ) {
      return methods.unstick.apply( this, arguments );
    } else {
      $.error('Method ' + method + ' does not exist on jQuery.sticky');
    }

  };
  $(function() {
    setTimeout(scroller, 0);
  });
})(jQuery);

Deze word opgeroepen door: <script src="http://test.com/testfixed.js" type="text/javascript"></script>
daarnaast staat in de head: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>

en als open code:
Code:
<script>
    $(window).load(function(){
      $("#customizedwelcometitel").sticky({ topSpacing: 0 });
    });
  </script>

Code:
<div id="customizedwelcometitel">

Zodra de open code op de site word gezet krijg je een blanco pagina.
Al ik de html file lokaal op de pc open werk t perfect.
Daarom vermoed ik dat er een conflict is tussen een andere functie die op de site draait.

Gr. Jop
 
Je moet even in je console kijken wat er precies mis gaat.
Zo open je console in Chrome:
Ctrl + Shift + J
 
Beste Total70,

Heb even met Chrome gekeken: Het gekke is dat er in het console niets te zien is.
Als ik dan de bronpagina erbij pak is deze leeg.
Daarom is er natuurlijk die witte pagina. Maar waarom ?

Het gebeurt zodra deze code in de pagina word gezet
Code:
<script>
    $(window).load(function(){
      $("#zoek").sticky({ topSpacing: 0 });
    });
  </script>
 
Laatst bewerkt:
Beste Total 70,

Bedankt voor deze code en hulp! Ben daar erg blij mee.
klopt het dat deze niet in Explorer (11) werkt?
In safari & Chrome werkt het perfect!

Code:
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Test</title>
  
  <script type='text/javascript' src='//code.jquery.com/jquery-2.1.0.js'></script>
  
  
  
  
  <link rel="stylesheet" type="text/css" href="/css/result-light.css">
  
  <style type='text/css'>
    	body {
		padding: 0;
		margin: 0;
	}
	.header {
		width: 100%;
		height: 75px;
		background: blue;
		display: block;
	}
	.search {
		width: 150px;
		height: 25px;
		background: green;
		position: absolute;
		top: 150px;
	}
	.container {
		display: block;
		height: 3000px;
	}
  </style>
  


<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
$(function(){
	$(window).scroll(function(){
		if(window.scrollY >= 150 ) {
			$(".search").css({
				position: "fixed",
				top: 0
			});
		} else {
			$(".search").css({
				position: "absolute",
				top: 150
			});
		}

	});
});
});//]]>  

</script>


</head>
<body>
  <div class="header">
	
</div>
<div class="search">
	
</div>
<div class="container">
	
</div>
  
</body>


</html>


gr. Jop
 
Bedankt total70 :)

Nog een vraag over dit onderwerp. Op de hoofdsite is het noodzakelijk om scripts tussen {literal} tags te zetten.

Code:
{literal}
 <script>
        // DOM Ready
    $(function(){
    $(window).scroll(function(){
        console.log(window.scrollY)
        if(window.pageYOffset >= 100 ) {
            $(".nav").css({
                position: "fixed",
                top: 0
            });
        } else {
            $(".nav").css({
                position: "absolute",
                top: 100
            });
        }

    });
}); 
    </script>
{/literal}

Hoe kan het dat hij dan niet meer werkt?
 
Hallo,

Zie net jullie topic :)
Code:
 $(function(){
            $(window).scroll(function() {
            var scroll = getCurrentScroll();
                if ( scroll >= 100 ) {
                    $('.fixedSwitch').addClass('Fixed');
                } else {
                    $('.fixedSwitch').removeClass('Fixed');
   
                }
            });

Hoe krijg ik dit nu werkend, en klopt mijn code?

Gr. Yoeri
 
Status
Niet open voor verdere reacties.
Terug
Bovenaan Onderaan