I'm trying to get my window resize to work but I have to update the page every time to get it to work. Is there any way that this can update dynamic??
$(document).ready(function() {
var $window = $(window);
function checkWidth() {
var window_size = $window.width();
if(window_size> 1820){
$('.22').addClass('size33');
$('.22').removeClass('size22');
} else {
$('.22').removeClass('size33');
$('.22').addClass('size22');
}
}
// Execute on load
checkWidth();
// Bind event listener
$(window).resize(checkWidth);
});
var div = document.body.selectElementbyId("div id")
window.addEventListener('resize', function() {
var window_size = $window.width();
if(window_size> 1820){
$('.22').addClass('size33');
$('.22').removeClass('size22');
} else {
$('.22').removeClass('size33');
$('.22').addClass('size22');
}
document.getElementbyId("div id").style.width = window_size;
}
}, true);
Related
I currently have this function:
function highlightBoxes() {
var windowStart = $(window).scrollTop();
var windowEnd = windowStart + $(window).height();
$('.box').each(function() {
var box = $(this);
var start = box.offset().top;
var end = start + box.height();
if (windowStart <= start && windowEnd >= end) {
box.addClass('active');
} else {
box.removeClass('active');
}
});
}
highlightBoxes();
$(document).scroll(highlightBoxes);
$(window).resize(highlightBoxes);
Which checks if an entire element (in this case .box) is in view (jsfiddle). However, I want to be able to use the function as an on event, so I can use it for many different elements. Something like:
$('.box').on('inview', function () {
if (elementIsInView) {
// make the box red
} else {
// make the box the original color
}
});
How can I do this?
using on means you will need to trigger an event with the same name, a super simple version of this is using document as the message bus like:
$(document).trigger('inview');
Therefore at the point in your code where you have decided that inview should be true, fire an event like the above, at which point the on event will run the function.
Base on the code above, you probably want to move the if statement out of the on event, and in fact run that as a separate function. When elementIsInView returns true, you could fire the inview event.
You could use the hover event.
$(document).on('hover','.box', function () {
if (elementIsInView) {
// make the box red
} else {
// make the box the original color
}
});
If am not clear with your answer let me know.
click ,hover ,drag all are events. Event is a action, apply from user. Function is a declare with javascript.Is not directly running.Its only run after event trigger.Event are declared by w3c
I think you need something like that:
Assign function with button click.Its works from button click event.
$('button').on('click',hello)
function hello(){
console.log('button Clicked')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button >hi</button>
or
$('button').on('click',function hello(){
console.log('button Clicked')
})
For your code do like this
$('.box').on('click', function inview() {
if (elementIsInView) {
// make the box red
} else {
// make the box the original color
}
});
try this:
function checkElementToBeInView(elem, callback) {
$(elem).each(function() {
var element = $(this);
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = element.offset().top;
var elemBottom = elemTop + element.height();
var isInView = ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
callback(element, isInView);
});
}
$(window).on("load resize scroll", function(e) {
checkElementToBeInView(".box", function(elem, isInView) {
if (isInView)
elem.addClass('active');
else
elem.removeClass('active');
});
I do what something like:
$('div > img').onAll('load', function() { alert('Loaded!') })
Which would alert "Loaded!" only once
I don't want this:
$('div > img').on('load', function() { alert('Loaded!'); });
because this would call the event after every single image has been loaded
Is there any ready function in jQuery that calls an event on a set of matches? Or do I have to write a custom function for it?
Create your own method
$.fn.onAll = function(ev, callback) {
var xhr = [];
this.each(function() {
var def = new $.Deferred();
var ele = document.createElement(this.tagName.toLowerCase());
ele['on'+ev] = function() {
def.resolve();
}
ele.src = this.src;
xhr.push(def);
});
$.when.apply($, xhr).then(callback);
return this;
}
to be used as
$('div > img').onAll('load', function() { alert('Loaded!'); });
FIDDLE
Try this
var $images = $("div > img")
, imageCount = $images.length
, counter = 0;
// one instead of on, because it need only fire once per image
$images.one("load",function(){
// increment counter everytime an image finishes loading
counter++;
if (counter == imageCount) {
// do stuff when all have loaded
alert('Loaded!');
}
}).each(function () {
if (this.complete) {
// manually trigger load event in
// event of a cache pull
$(this).trigger("load");
}
});
try something like this
$('body').on('load','div > img',function() { alert('Loaded!') });
Happy Coding :)
I want to make the sticky-nav to act similar(scroll is off when the menu is expanded) to this website's nav(http://amandagerhardsen.com/#cloudbusting/4) when expanded.
How do I do it?
var Boxlayout = (function () {
var $el = $('#sticky-nav'),
$sections = $el.children('section'),
// work panels
$workPanelsContainer = $('#bl-panel-work-items'),
// close work panel trigger
$closeWorkItem = $workPanelsContainer.find('nav > span.hidemenu'),
transEndEventNames = {
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'transitionend',
'OTransition': 'oTransitionEnd',
'msTransition': 'MSTransitionEnd',
'transition': 'transitionend'
},
// transition end event name
transEndEventName = transEndEventNames[Modernizr.prefixed('transition')],
// support css transitions
supportTransitions = Modernizr.csstransitions;
function init() {
initEvents();
}
function initEvents() {
$sections.each(function () {
var $section = $(this);
// expand the clicked section and scale down the others
$section.on('click', function () {
if (!$section.data('open')) {
$section.data('open', true).addClass('bl-expand bl-expand-top');
$el.addClass('bl-expand-item');
}
}).find('span.hidemenu').on('click', function () {
// close the expanded section and scale up the others
$section.data('open', false).removeClass('bl-expand').on(transEndEventName, function (event) {
if (!$(event.target).is('section')) return false;
$(this).off(transEndEventName).removeClass('bl-expand-top');
});
if (!supportTransitions) {
$section.removeClass('bl-expand-top');
}
$el.removeClass('bl-expand-item');
return false;
});
});
// clicking on a work item: the current section scales down and the respective work panel slides up
$workItems.on('click', function (event) {
// scale down main section
$sectionWork.addClass('bl-scale-down');
// show panel for this work item
$workPanelsContainer.addClass('bl-panel-items-show');
var $panel = $workPanelsContainer.find("[data-panel='" + $(this).data('panel') + "']");
currentWorkPanel = $panel.index();
$panel.addClass('bl-show-work');
return false;
});
// navigating the work items: current work panel scales down and the next work panel slides up
$nextWorkItem.on('click', function (event) {
if (isAnimating) {
return false;
}
isAnimating = true;
var $currentPanel = $workPanels.eq(currentWorkPanel);
currentWorkPanel = currentWorkPanel < totalWorkPanels - 1 ? currentWorkPanel + 1 : 0;
var $nextPanel = $workPanels.eq(currentWorkPanel);
$currentPanel.removeClass('bl-show-work').addClass('bl-hide-current-work').on(transEndEventName, function (event) {
if (!$(event.target).is('div')) return false;
$(this).off(transEndEventName).removeClass('bl-hide-current-work');
isAnimating = false;
});
if (!supportTransitions) {
$currentPanel.removeClass('bl-hide-current-work');
isAnimating = false;
}
$nextPanel.addClass('bl-show-work');
return false;
});
// clicking the work panels close button: the current work panel slides down and the section scales up again
$closeWorkItem.on('click', function (event) {
// scale up main section
$sectionWork.removeClass('bl-scale-down');
$workPanelsContainer.removeClass('bl-panel-items-show');
$workPanels.eq(currentWorkPanel).removeClass('bl-show-work');
return false;
});
}
return {
init: init
};
})();
Here is a fiddle: http://jsfiddle.net/77P2e/
Be careful to unlock scrolling again when done, or this could be very annoying for the user!
Setup code
var $window = $(window), previousScrollTop = 0, scrollLock = false;
$window.scroll(function(event) {
if(scrollLock) {
$window.scrollTop(previousScrollTop);
}
previousScrollTop = $window.scrollTop();
});
To lock scroll position:
scrollLock = true;
And to unlock again...
scrollLock = false;
As an example use, you could lock the window scroll position when the mouse enters the navigation area, and unlock it again when the mouse leaves:
$("nav")
.mouseenter(function(){ scrollLock = true; })
.mouseleave(function(){ scrollLock = false; });
In my opinion the accepted answer is not what should be achieved, as the window.scroll() function will be still running (endlessly), even if the 'event' has occured.
The window.scroll() function is an event handler. So use on() to bind the event and off() to unbind it (after the 'event' has occured).
$(window).on('scroll', function() { // bind event handler
var offset = $(window).scrollTop();
console.log("page Y-Offset: ", offset); // just to see it working
if(offset >= 100) $(window).off('scroll'); // unbind the event handler when the condition is met
});
The Javascript solution is a little janky for me, on mobile. It's like it scrolls a little bit and then snaps back into place.
However, I figured out a way to do it much more cleanly, without any jank, just by changing CSS's overflow property on the part you don't want to scroll. Here's the code in d3 but the concept should be pretty clear:
var body = d3.select('body');
var preventScroll = function () {
body.style('overflow', 'hidden');
},
allowScroll = function () {
body.style('overflow', 'scroll');
};
d3.select('#sticky-nav')
.on('touchmove', preventScroll)
.on('touchstart', preventScroll)
.on('touchend', allowScroll)
.on('touchcancel', allowScroll);
As I was using jquery animation,
if ($(window).scrollTop() >= $('.btn').offset().top + $('.btn').outerHeight() - window.innerHeight)
{
$(".tab").stop();
}
I did this and it worked.
.btn is the button. That .tab div would stop if it scrolls to that position.
If you're using jquery animation you can try using the stop() function on the animated object.
I have this js that I want to only run when the screen size is 800 or below, as it enables swiping. Please help I cant figure out away.
var snapper = new Snap({
element: document.getElementById('content')
});
and the Snap is linked by
Thanks for any help.
EDIT:
<script>
$(function() {
var SmartMenu = $('#SmartMenu');
MainMenu = $('.MainMenu');
PortfolioMenu = $('#Portfolio');
PortfolioSubMenu = $('.subMenu');
SmartMenuOpen = $('#SmartMenuOpen');
wrapperHeader = $('.wrapperHeader-Top');
if(window.innerWidth <= 800) {
var snapper = new Snap({
element: document.getElementById('W')
});
}
$(SmartMenu).on('click', function(a) {
if( snapper.state().state=="left" ){
snapper.close();
} else {
snapper.open('left');
}
});
</script>
if(window.innerWidth <= 800) {
// Your code here
}
That should do the trick the first time.
EDIT 1:
If you want it to change whenever the browser is resized
window.onresize = function(event) {
if(window.innerWidth <= 800) {
// Your code here
}
}
But do make sure that the code you include will work correctly if called multiple times when the browser is resized.
EDIT 2 With access to jQuery: #2 to support Snap API and to support init
var snapper;
function initSnapper() {
if($(window).innerWidth() <= 800) {
if(snapper === undefined) {
snapper = new Snap({
element: document.getElementById('W')
});
}
else {
snapper.enable();
}
}
else if(snapper !== undefined) {
snapper.disable();
}
}
$(window).resize(initSnapper);
initSnapper();
This will initialize snapper when the page loads and will call initSnapper when the page is resized.
And you will want to check if snapper exists before checking the state like
if( snapper && snapper.state().state=="left" ){
// snapper code
}
How can I call for this(or any) JS function to be run again whenever the Browser window is resized?
<script type="text/javascript">
function setEqualHeight(e) {
var t = 0;
e.each(function () {
currentHeight = $(this).height();
if (currentHeight > t) {
t = currentHeight
}
});
e.height(t)
}
$(document).ready(function () {
setEqualHeight($(".border"))
})
</script>
You can use the window onresize event:
window.onresize = setEqualHeight;
You can subscribe to the window.onresize event (See here)
window.onresize = setEqualHeight;
or
window.addEventListener('resize', setEqualHeight);
This piece of code will add a timer which calls the resize function after 200 milliseconds after the window has been resized. This will reduce the calls of the method.
var globalResizeTimer = null;
$(window).resize(function() {
if(globalResizeTimer != null) window.clearTimeout(globalResizeTimer);
globalResizeTimer = window.setTimeout(function() {
setEqualHeight();
}, 200);
});
You use jquery, so bind it using the .resize() method.
$(window).resize(function () {
setEqualHeight( $('#border') );
});