Javascript error if element is not on the page - javascript

I want to have a single script file for every page, which has scripts which may or may not be required for that particular page. On my homepage I have this script:
$(function () {
var $select = $('#select');
var $window = $(window);
var isFixed = false;
var init = $('#select').offset().top;
$window.scroll(function () {
var currentScrollTop = $window.scrollTop();
if (currentScrollTop > init && isFixed === false) {
isFixed = true;
$select.css({
top: 0,
position: 'fixed'
});
console.log("fixed");
} else if(currentScrollTop <= init && isFixed === true) {
isFixed = false;
$select.css('position', 'relative');
console.log("unfixed");
}
});
$("#scroll").click(function () {
$('html, body').animate({
scrollTop: $(".jumbo").offset().top + $(".jumbo").height()
}, 300);
});
});
However when this runs on the homepage (which doesnt have the #select element) I get this error and breaks my script:
Uncaught TypeError: Cannot read property 'top' of undefined
How can I get it to not cause errors if that script isnt required on that particual page without having to load it in its own file?
Should I have it call the function on page load?

You can use the length property to check if an element exists:
var init = $select.length ? $select.offset().top : 0;
This will return 0 if the element is not present, otherwise its top offset.

Related

Understanding Jquery function - $(document).ready(callback);

Hi am trying to run a function on window resize and document ready. As resize is triggered by mobile scroll it is necessary to check the height hasn't changed. This code works for resize but not on load. Is anyone able to explain whey the function isn't executed on document ready? Thanks in advance.
//CLOSE EXPANDED ELEMENTS FOR MOBILE
var $window = $(window);
var width = $(window).width();
var callback = function () {
if($(window).width() != width){
if ($window.width() < 756) {
$(".content_lower.collapse").removeClass('in');
}
else {
$(".content_lower.collapse").addClass('in');
}
}
};
$(document).ready(callback);
$(window).resize(callback);
console.log(callback.toString());
Actually on document ready the document is just loaded and the $(window).width() is equal to width variable.
So the function callback will be called while width = $(window).width() so it will not enter the if condition and nothing will happen inside the function.
If you try to log somtheing to the console or alert a message in the beginning of your function you will see that it's executed:
var callback = function() {
console.log("Callback entered !!!");
if ($(window).width() != width) {
if ($window.width() < 756) {
$(".content_lower.collapse").removeClass('in');
} else {
$(".content_lower.collapse").addClass('in');
}
}
};
EDIT:
If you still want to execute it in document load you can add a boolean flag initialized to false and set it to true if the window is once resized then test with it:
var $window = $(window);
var width = $(window).width();
var called = false;
var callback = function() {
console.log("callback entered !!!");
if ($(window).width() != width || !called) {
if ($window.width() < 756) {
$(".content_lower.collapse").removeClass('in');
} else {
$(".content_lower.collapse").addClass('in');
}
}
called = true;
};
$(document).ready(callback);
$(window).resize(callback);
console.log(callback.toString());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content_lower.collapse">the div</div>
EDIT 2:
A better approach is to use the boolean flag as a parameter of the callback function, and call it with false on document load and true on window resize:
var $window = $(window);
var width = $(window).width();
var callback = function(resized) {
if ($(window).width() != width || !resized) {
if ($window.width() < 756) {
$(".content_lower.collapse").removeClass('in');
} else {
$(".content_lower.collapse").addClass('in');
}
}
};
$(document).ready(callback(false));
$(window).resize(callback(true));
This gave the desired effect. Tanks for the help guys.
var $window = $(window);
var width = $(window).width();
var callback = function () {
if ($window.width() < 756) {
$(".content_lower.collapse").removeClass('in');
}
else {
$(".content_lower.collapse").addClass('in');
}
};
$(document).ready(callback);
$( window ).resize(function() {
if($(window).width() != width){
callback();
}
});
When the document is loaded the width variable will be set to your window-width (let's say 500px). Then it checks if the current window-width (so 500px) is equal to the width var (500 !== 500). This returns false, so you code won't be executed. You can do this instead:
var callback = function() {
if ($(window).width() < 756) {
$('body').text($(window).width() + " - if");
} else {
$('body').text($(window).width() + " - else");
}
};
$(document).ready(callback);
$(window).resize(callback);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

jQuery animation with interval not working

Basically I want my piece of code to animate my menu out of the screen hence my -50px on scroll. and when not scrolling animate back in.
This is the code I have so far. but It only works on every time I refresh my browser.
var $menu = $(".sticky-nav");
var topAnim = $menu.css("top");
var scrollStopped;
var fadeInCallback = function () {
if (typeof scrollStopped != 'undefined') {
clearInterval(scrollStopped);
}
scrollStopped = setTimeout(function () {
$( ".sticky-nav" ).animate({
top: "20px"
}, 300);
});
}
$(window).scroll(function () {
if (!$menu.is(":animated") && topAnim == "20px") {
$( ".sticky-nav" ).animate({
top: "-50px"
}, 300);
} else {
fadeInCallback.call(this);
}
});
jsfiddle.net/B997S
I found 2 issues in your code.
Replaced topAnim in the below line with $menu.css("top") as topAnim always returned a constant.
if (!$menu.is(":animated") && $menu.css("top") == "20px") {
Next issue was
scrollStopped = setInterval(function () { // this is the right format
Please check the below link
http://jsfiddle.net/kapilgopinath/B997S/1/

Prevent scrolling jquery script from running twice

I'm new to jquery and have put together the following code to make a DIV appear after a set scroll-down amount. If scrolling back up, the DIV disappears. Optionally, once the DIV has appeared, there is a link to close it. This all works as intended, apart from that I only want the script to run once. At the moment if I scroll back up, the yellow box appears again. How can I ensure the box stays closed? As another option, could I integrate cookies or localStorage?
Many thanks! Russ.
Javascript:
$(function () {
var target = $(".box");
if ($(window).scrollTop() > 30) {
target.hide();
}
$(window).scroll(function () {
var pos = $(window).scrollTop();
if (pos > 30) {
target.stop(true, true).fadeIn('slow');
} else {
target.stop(true, true).fadeOut('slow');
}
});
$('a.close').click(function () {
$($(this).attr('href')).slideUp();
return false;
});
});
Here is the jsfiddle link to my code: jsfiddle link
You can remove the class to ensure the box stays enclosed with removeClass(). Or directly $(".box").remove() after your animation.
You can store this choice with cookie but if the client deletes his cookies, it's lost.
You can remove event scroll from window and for localStorage do something like that:
$(function () {
var target = $(".box");
if ($(window).scrollTop() > 30) {
target.hide();
}
$(window).scroll(function () {
var pos = $(window).scrollTop();
if (pos > 30) {
target.stop(true, true).fadeIn('slow');
} else {
target.stop(true, true).fadeOut('slow');
}
if(localStorage['noNotification'] == 'true'){
$(window).off('scroll');
}
});
$('a.close').click(function () {
$($(this).attr('href')).slideUp();
$(window).off('scroll');
localStorage['noNotification'] = 'true';
return false;
});
});
try this http://jsfiddle.net/AbwXu/4/
var notdisplayed=true;
$(function(){
var target = $(".box");
if($(window).scrollTop() > 30){
target.hide();
}
$(window).scroll(function(){
var pos = $(window).scrollTop();
if(pos > 30 && notdisplayed){
target.stop(true, true).fadeIn('slow');
} else {
target.stop(true, true).fadeOut('slow');
notdisplayed=false;
}
});
$('a.close').click(function() {
$($(this).attr('href')).slideUp();
notdisplayed=false;
return false;
});

jQuery Scroll Current Position and Next-Prev Navigator

I need a bit of advice as I can't get my noob head around the following, please see this fiddle: http://jsfiddle.net/NtUpw/
The code works as intended, but when the current div offset goes > 41 and prev is hit, I'd like the page to return to the beginning of the current div, not to one before that. Any idea how can I add this condition?
I realise the current code isn't the cleanest (actually it's a combination of two fiddles), but I hope someone could take a look at it anyway. Thanks.
$('a.buttons').on('click', function (e) {
e.preventDefault();
var t = $(this).text(),
that = $(this);
if (t === 'next' && $('.current').next('div.post').length > 0 ) {
var $next = $('.current').next('.post');
var top = $next.offset().top;
$('body').animate({
scrollTop: $('.current').next('div.post').offset().top - 40
});
} else if (t === 'prev' && $('.current').prev('div.post').length > 0 ) {
var $prev = $('.current').prev('.post');
var top = $prev.offset().top;
$('body').animate({
scrollTop: $('.current').prev('div.post').offset().top - 40
});
}
$(window).bind('scroll', function () {
$('.post').each(function () {
var post = $(this);
var position = post.position().top - $(window).scrollTop();
if (position <= 40) {
post.addClass('current');
post.prev().removeClass("current");
} else {
post.removeClass('current');
}
});
});
The prev action works by moving always the div to the previous; the solution is to check the current position of the navigator respect to the current div:
var $prev;
var top;
var firstElem = true;
if ($('.current').prev('div.post').length > 0) {
$prev = $('.current').prev('.post');
top = $prev.offset().top;
firstElem = false
}
var currTop = $('.current').offset().top;
var navBottom = $('.navigation').offset().top + 40;
if (currTop == navBottom && !firstElem) {
$('body,html').animate({
scrollTop: $('.current').prev('div.post').offset().top - 40
});
with this the navigator jumps to the previous div only if is not at the top of the current; alternatively jumps to the previous.
The firefox issue depends on how Firefox places the overflow, it places it at the html level not at body like other browsers.
To let it work you must define the scrolling action with:
$('body,html').animate({
});
Working fiddle: http://jsfiddle.net/IrvinDominin/2QYgR/3/

jquery code does not work fine with differents urls

I have this jquery code:
$(function(){
var $win = $(window);
var $nav = $('.subnav');
var navTop = $('.subnav').length && $('.subnav').offset().top - 38;
var isFixed = 0;
processScroll();
$win.on('scroll', processScroll);
function processScroll() {
console.log('test');
var i, scrollTop = $win.scrollTop();
if (scrollTop >= navTop && !isFixed) {
isFixed = 1;
$nav.addClass('subnav-fixed');
} else if (scrollTop <= navTop && isFixed) {
isFixed = 0;
$nav.removeClass('subnav-fixed');
}
};
})
If I have this url for example:
http://mydomain.com/posts or http://mydomain.com or http://mydomain.com/post?utf8=✓&search=
the code does works fine, but if I have for example:
http://mydomain.com/post?utf8=✓&search=port or http://mydomain.com/post?utf8=✓&search=word
The code does not works fine...
Why if I pass a param for url with my search engine the code does not works fine?
Thank you very much!
Edited
I am using this sunspot solr for my as search engine
http://sunspot.github.com/
I found the fix in this question:
Replicating Bootstraps main nav and subnav
This is the code:
$(document).scroll(function(){
// If has not activated (has no attribute "data-top"
if (!$('.subnav').attr('data-top')) {
// If already fixed, then do nothing
if ($('.subnav').hasClass('subnav-fixed')) return;
// Remember top position
var offset = $('.subnav').offset()
$('.subnav').attr('data-top', offset.top);
}
if ($('.subnav').attr('data-top') - $('.subnav').outerHeight() <= $(this).scrollTop())
$('.subnav').addClass('subnav-fixed');
else
$('.subnav').removeClass('subnav-fixed');
});
Thank you

Categories