Change Position of div in javascript - javascript

I want to Change Positioning of HTML div Via Javascript in my existing Script
Currently This My Existing Javascript is generating in front end.
<div class="navbar navbar-inverse affix" id="SubMenu" style="top: 72px;">
But i want to make positioning to top:8px
JavaScript is as Below.
// Sub-navbar affix on scroll
// ------------------------------------------------------------------------
if ($('#SubMenu').length) {
$('#SubMenu').affix({
offset: {
top: function() {
return $('#SubMenu').parent().offset().top - $('#navbar-main-container').outerHeight();
},
}
}).css('top', $('#navbar-main-container').outerHeight());
// Update values on window resize
$(window).resize(function() {
theTop = $('#SubMenu').parent().offset().top - $('#navbar-main-container').outerHeight();
$('#SubMenu').data('bs.affix').options.offset = {
top: theTop
};
});
$('#SubMenu').on('affixed.bs.affix', function() {
$('a.navbar-brand.scrollTop span').text($('#destination-the-title').val());
});
$('#SubMenu').on('affixed-top.bs.affix', function() {
setTimeout(function() {
$('a.navbar-brand.scrollTop span').text('');
}, 600)
});
}

Since you are using jQuery just use the following line of code.
$("#SubMenu").css("top","8px");
To be more precise
instead if this part
.css('top', $('#navbar-main-container').outerHeight());
add .css("top","8px");

Related

How to call a div height in jQuery and set it into the css of another div dynamically (upon window resizing)? [duplicate]

I have the following JQuery code:
$(document).ready(function () {
var $containerHeight = $(window).height();
if ($containerHeight <= 818) {
$('.footer').css({
position: 'static',
bottom: 'auto',
left: 'auto'
});
}
if ($containerHeight > 819) {
$('.footer').css({
position: 'absolute',
bottom: '3px',
left: '0px'
});
}
});
The only problem is that this only works when the browser first loads, I want containerHeight to also be checked when they are resizing the window?
Any ideas?
Here's an example using jQuery, javascript and css to handle resize events.
(css if your best bet if you're just stylizing things on resize (media queries))
http://jsfiddle.net/CoryDanielson/LAF4G/
css
.footer
{
/* default styles applied first */
}
#media screen and (min-height: 820px) /* height >= 820 px */
{
.footer {
position: absolute;
bottom: 3px;
left: 0px;
/* more styles */
}
}
javascript
window.onresize = function() {
if (window.innerHeight >= 820) { /* ... */ }
if (window.innerWidth <= 1280) { /* ... */ }
}
jQuery
$(window).on('resize', function(){
var win = $(this); //this = window
if (win.height() >= 820) { /* ... */ }
if (win.width() >= 1280) { /* ... */ }
});
How do I stop my resize code from executing so often!?
This is the first problem you'll notice when binding to resize. The resize code gets called a LOT when the user is resizing the browser manually, and can feel pretty janky.
To limit how often your resize code is called, you can use the debounce or throttle methods from the underscore & lodash libraries.
debounce will only execute your resize code X number of milliseconds after the LAST resize event. This is ideal when you only want to call your resize code once, after the user is done resizing the browser. It's good for updating graphs, charts and layouts that may be expensive to update every single resize event.
throttle will only execute your resize code every X number of milliseconds. It "throttles" how often the code is called. This isn't used as often with resize events, but it's worth being aware of.
If you don't have underscore or lodash, you can implement a similar solution yourself:
JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?
Move your javascript into a function and then bind that function to window resize.
$(document).ready(function () {
updateContainer();
$(window).resize(function() {
updateContainer();
});
});
function updateContainer() {
var $containerHeight = $(window).height();
if ($containerHeight <= 818) {
$('.footer').css({
position: 'static',
bottom: 'auto',
left: 'auto'
});
}
if ($containerHeight > 819) {
$('.footer').css({
position: 'absolute',
bottom: '3px',
left: '0px'
});
}
}
Try this solution. Only fires once the page loads and then during window resize at predefined resizeDelay.
$(document).ready(function()
{
var resizeDelay = 200;
var doResize = true;
var resizer = function () {
if (doResize) {
//your code that needs to be executed goes here
doResize = false;
}
};
var resizerInterval = setInterval(resizer, resizeDelay);
resizer();
$(window).resize(function() {
doResize = true;
});
});
jQuery has a resize event handler which you can attach to the window, .resize(). So, if you put $(window).resize(function(){/* YOUR CODE HERE */}) then your code will be run every time the window is resized.
So, what you want is to run the code after the first page load and whenever the window is resized. Therefore you should pull the code into its own function and run that function in both instances.
// This function positions the footer based on window size
function positionFooter(){
var $containerHeight = $(window).height();
if ($containerHeight <= 818) {
$('.footer').css({
position: 'static',
bottom: 'auto',
left: 'auto'
});
}
else {
$('.footer').css({
position: 'absolute',
bottom: '3px',
left: '0px'
});
}
}
$(document).ready(function () {
positionFooter();//run when page first loads
});
$(window).resize(function () {
positionFooter();//run on every window resize
});
See: Cross-browser window resize event - JavaScript / jQuery
Give your anonymous function a name, then:
$(window).on("resize", doResize);
http://api.jquery.com/category/events/
function myResizeFunction() {
...
}
$(function() {
$(window).resize(myResizeFunction).trigger('resize');
});
This will cause your resize handler to trigger on window resize and on document ready. Of course, you can attach your resize handler outside of the document ready handler if you want .trigger('resize') to run on page load instead.
UPDATE: Here's another option if you don't want to make use of any other third-party libraries.
This technique adds a specific class to your target element so you have the advantage of controlling the styling through CSS only (and avoiding inline styling).
It also ensures that the class is only added or removed when the actual threshold point is triggered and not on each and every resize. It will fire at one threshold point only: when the height changes from <= 818 to > 819 or vice versa and not multiple times within each region. It's not concerned with any change in width.
function myResizeFunction() {
var $window = $(this),
height = Math.ceil($window.height()),
previousHeight = $window.data('previousHeight');
if (height !== previousHeight) {
if (height < 819)
previousHeight >= 819 && $('.footer').removeClass('hgte819');
else if (!previousHeight || previousHeight < 819)
$('.footer').addClass('hgte819');
$window.data('previousHeight', height);
}
}
$(function() {
$(window).on('resize.optionalNamespace', myResizeFunction).triggerHandler('resize.optionalNamespace');
});
As an example, you might have the following as some of your CSS rules:
.footer {
bottom: auto;
left: auto;
position: static;
}
.footer.hgte819 {
bottom: 3px;
left: 0;
position: absolute;
}
Use this:
window.onresize = function(event) {
...
}
can use it too
function getWindowSize()
{
var fontSize = parseInt($("body").css("fontSize"), 10);
var h = ($(window).height() / fontSize).toFixed(4);
var w = ($(window).width() / fontSize).toFixed(4);
var size = {
"height": h
,"width": w
};
return size;
}
function startResizeObserver()
{
//---------------------
var colFunc = {
"f10" : function(){ alert(10); }
,"f50" : function(){ alert(50); }
,"f100" : function(){ alert(100); }
,"f500" : function(){ alert(500); }
,"f1000" : function(){ alert(1000);}
};
//---------------------
$(window).resize(function() {
var sz = getWindowSize();
if(sz.width > 10){colFunc['f10']();}
if(sz.width > 50){colFunc['f50']();}
if(sz.width > 100){colFunc['f100']();}
if(sz.width > 500){colFunc['f500']();}
if(sz.width > 1000){colFunc['f1000']();}
});
}
$(document).ready(function()
{
startResizeObserver();
});
You can bind resize using .resize() and run your code when the browser is resized. You need to also add an else condition to your if statement so that your css values toggle the old and the new, rather than just setting the new.

Run a javascript function from HTML events

I'm working on a project that animate on page scroll.
This is the element I want to animate.
<h1 style="position: relative; top: 0; left: 0;"
onscroll="animateAfterPosition(200)"
data-animate-left="50px" data-animate-top="50px"
data-animate-time="0.2s">Animation on scroll</h1>
This is my JavaScript
function animateAfterPosition(scroll) {
console.log(scroll);
function(){
if (window.scrollY <= scroll) {
this.classList.add('animateAfterPosition');
} else {
this.classList.remove('animateAfterPosition');
}}
And this is my CSS
.animateAfterPosition {
transition: attr(data-animate-time);
left: attr(data-animate-left);
top: attr(data-animate-top);}
I need to run the function animateAfterPosition from the html. I expected to run the function with onscroll event, but it doesn't work. So how can I do this?
Edit
I found that css attr() is only working with the content: property and I managed to do it with JavaScript
You need to add selector to toggle class the animation. And your current css doesn't have enough height to make scrolling window. Here's an simple snippet to run your function onload, update onscroll and toggling class.
var dataAnimate = document.querySelector('[data-animate]');
function animateAfterPosition(scroll) {
dataAnimate.classList.toggle('active', window.scrollY <= scroll);
}
window.addEventListener("scroll", function() {
return animateAfterPosition(200);
});
.animateAfterPosition {
transition: attr(data-animate-time);
left: attr(data-animate-left);
top: attr(data-animate-top);
}
[data-animate] {
height: 1000px;
}
<body onload="animateAfterPosition(200)">
<h1 style="position: relative; top: 0; left: 0;"data-animate-left="50px" data-animate-top="50px" data-animate-time="0.2s" data-animate>Animation on scroll</h1>
</body>
Fiddle: https://jsfiddle.net/rafonzoo/phmg0u46/
A minimalistic solution
You can configure it using the first 4 variables in the function. I recommend adding the indicator class to the body itself and then use a selector like body.beyond-that-point h1. This way, it's possible to make several tags behave differently as the scrolling happens.
You can test it here
This version uses a fancier effect but the logic behind is the same.
https://deneskellner.com/stackoverflow-examples/62623588/index.html
<!doctype html>
<html>
<style>
body.beyond-that-point {background:silver;}
div.text {padding:75vh 0px;text-align:center;}
</style>
<body>
<div class="text">
Scroll me down and the background will change
</div>
<script>
setTimeout(function() {
var amount = 100; // how many pixels before the miracle happens
var beyondClass = 'beyond-that-point'; // this class will be added
var targetSelector = 'body'; // which element to add the class to
var checkMS = 20; // check scroll position every N milliseconds
var eClass = document.querySelector(targetSelector).classList;
setInterval(function() {
var y = window.scrollY;
var c = beyondClass;
var isBeyond = !!(y>=amount)?1:0;
if(isBeyond==1) if(!eClass.contains(c)) eClass.add(c);
if(isBeyond==0) if( eClass.contains(c)) eClass.remove(c);
},checkMS);
},1);
</script>
</body>
</html>
Note: there are better ways to check DOM readiness but for simplicity I used setTimeout here. Feel free to change it.

custom cursor change based on cursor position - Royalslider

I’m using royalslider. I have a function which allows navigation depending on cursor position.
}).data('royalSlider');
slider.ev.on('rsSlideClick', function(e, origEvent) {
var width = jQuery('.royalSlider').data('royalSlider').width;
if (origEvent.pageX < (width/2)) {
slider.prev();
$('.rsOverflow').css({
'cursor': 'url(images/prevg.png), default'
});
} else {
slider.next();
$('.rsOverflow').css({
'cursor': 'url(images/nextg.png), default'
});
};
});
});
How can I modify this so that cursors change on hover - not just after click. Thanks
That would work if you change the css at that point trough javascript (jQuery).
For my solution you would hav to implement jQuery in your html before you use your following script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Than the code below would change the cursor
var slider = $('#full-width-slider').royalSlider({
autoHeight: true,
///// more options /////
navigateByClick: false,
prefix: 'image-'
},
}).data('royalSlider');
slider.ev.on('rsSlideClick', function(e, origEvent) {
var width = jQuery('.royalSlider').data('royalSlider').width;
if (origEvent.pageX < (width/2)) {
slider.prev();
// change css to prevg.png
$('.rsOverflow').css({
"cursor" : "url('images/prevg.png'), auto !important;"
});
} else {
slider.next();
// change css to nextg.png
$('.rsOverflow').css({
"cursor" : "url('images/nextg.png'), auto !important;"
});
};
});
});
Now that I saw your Example. I can't see a simple way of using the existing functions. Now you could try this:
var mContainer = $('body'),
left = $(window).width() / 2,
x,
y;
$(window).mousemove(function(evt){
x = (evt.pageX - mContainer.offset().left) + $(window).scrollLeft();
if(x < left) {
$('.rsOverflow').css({
"cursor" : "url('images/prevg.png'), auto !important;"
});
} else {
$('.rsOverflow').css({
"cursor" : "url('images/nextg.png'), auto !important;"
});
}
});
I am calculating the offset position of the cursor on the X-Axis. Now you can check if the cursor is on the left part of the site or on the right part. An can change the cursor accordingly. Hope that helps!
I believe the best way is just to use two overlaying divs and remove them on touch as Yuri suggested. As the
hover event is not written into the code its difficult to detect.
<script type="text/javascript">
jQuery(function($){
if(typeof ontouchstart !== 'undefined'){
$('.prev1, .next1').remove();
}
});
</script>

Dynamically recalculate Bootstrap Affix's offset() on jQuery click event

In my app, I have two jQuery functions:
The first manages a simple slideToggle:
$( ".js-support-toggle" ).click(function(e) {
e.preventDefault();
$('.filter-weight').toggleClass('open');
$('.filter-weight .dropdown-body').slideToggle();
});
And corresponding markup:
<section class="dropdown filter-weight">
<a class="dropdown-title js-filter-toggle">Filter</a>
<div class="dropdown-body">
...
</div><!-- /dropdown-body-->
</section>
The second uses Bootstrap Affix to pin a secondary nav to the top of the page:
/* Affixes sidebar nav to top of screen */
$('#scrollspy').affix({
offset: {
top: function () {
return (this.top = $('.header-wrapper').outerHeight(true) + $('.filter-weight').outerHeight(true) + $('.secondary-navigation').outerHeight(true) + $('.filter-weight').outerHeight(true) + 100)
},
bottom: function () {
return (this.bottom = $('.footer').outerHeight(true))
}
}
})
That offset is determined by gathering the outerHeight() values of every element that comes above the affixed menu—including my slideToggled .filter-weight element.
This all works fabulously when that .filter-weight element is collapsed. However, if a user toggles it open, and then scrolls down the page, the added height of the toggled element throws off my offset calculation.
How could I rewrite my offset() to dynamically adjust to the variable height of my .filter-weight element?

lock a div on header when window scrolled past element

I want a circle div to lock in the header when the user scrolls past in.
I'm using the following code but it doesn't work
var circle$ = $('.circle'),
oCircleBottom = circle$.offset().top + circle$.outerHeight(true),
window$ = $(window);
window$.scroll(function() {
if (window$.scrollTop() > oCircleBottom) {
}
}.bind(this));
I want to perform an action when the user scrolls pass the circle div; however, the code above does not seem to work. Is oCircleBottom computed correctly?
Enclose your code in $(document).ready function
$(document).ready(function () {
var circle$ = $('.circle'),
oCircleBottom = circle$.offset().top + circle$.outerHeight(true),
window$ = $(window);
window$.scroll(function () {
if (window$.scrollTop() > oCircleBottom) {
$('.circle').css({
position: 'fixed',
top: '0',
left: '0'
});
}
else{
$('.circle').css({
position: 'static'});
}
}.bind(this));
});
You need to take window height into account because if the height of the page isnt enough to scroll down, your code doesnt work. Take a look at this example
However, if the increase page height, you code will work fine without subtracting window height. Take a look at this example
Hence, its better to subtract the window height. jsFiddle
$(window).bind('scroll', function() {
if($(window).scrollTop() >= $('.circle').offset().top + $('.circle').innerHeight() - window.innerHeight) {
//Do you stuff
}
});

Categories

Resources