Scrolling and .addClass(); issues - javascript

I am working on a "one page" website with a fixed navigation and about 5 different pages inside the one document.
UPDATED WORKING LINK
http://www.coco-works.com/Archive/ LIVE VERSION
I'm having trouble with the active class addition. When you click Keep in Touch or Home, the class is not applied. As you can see from the live version, it's not function properly.
The page works something like this;
And here is the JavaScript;
$(document).ready(function() {
$('body').click(function(event) {
if (event.target.nodeName.toLowerCase() == 'a') {
var op = $(event.target);
var id = op.attr('href');
if (id.indexOf('#') == 0) {
$.scrollTo(id, 1000, {
offset: {
top: 75
},
axis: 'y',
onAfter: function() {
window.location.hash = id.split('#')[1];
}
});
}
return false;
}
});
$.fn.waypoint.defaults.offset = 75;
$('.section h1.page_name').waypoint(function() {
var id = this.id;
var op = $('#navigation a[href = "#' + id + '"]');
if (op.length) {
$("#navigation a").removeClass("active");
op.addClass('active');
}
});
});
I'm not a strong programmer. I've tried to edit it as best as I can and I'm just stuck. Any insight to fixing this would highly be appreciated.
Still looking for an answer, below couldn't fix the problem.

I'm not sure what the waypoints plugin was doing, but I've refactored your code and it is working for me. Note that I took out the call to .waypoints, and changed your $('body').click() handler to be a more specific handler on the navigation link elements. This handler will scroll to each element and then will perform the removal and addition of the class correctly when the scrolling is done:
$(document).ready(function()
{
function highlightNav(navElement){
$("#navigation a").removeClass('active');
navElement.addClass('active');
}
$('#navigation a').click(function(event){
var nav = $(this);
var id = nav.attr('href');
$.scrollTo(id, 1000, {
offset: { top: -75 },
axis: 'y',
onAfter: function(){
highlightNav(nav);
}
});
return false;
});
$(window).scroll(function(){
if($(this).scrollTop() == 0){
highlightNav($("#navigation a[href*='home']"));
}
});
$.fn.waypoint.defaults.offset = 75;
$('.section h1.page_name').waypoint(function() {
var id = this.id;
var op = $('#navigation a[href = "#' + id + '"]');
if (op.length) {
highlightNav(op);
}
});
// Fancybox
$("a.zoom").fancybox({
'overlayShow' : false,
'transitionIn' : 'elastic',
'transitionOut' : 'elastic'
});
$("a.outside_shade").fancybox({
'titlePosition' : 'outside',
'overlayColor' : '#000',
'overlayOpacity' : 0.9
});
$("a.inside_white").fancybox({
'titlePosition' : 'inside'
});
$("a.inside_shade").fancybox({
'titlePosition' : 'over'
});
// validation
$("form").validate();
// nivo slider
$('#slider').nivoSlider();
});
In the html I added a default active class to the first link:
<div id="navigation">
<ul>
<li>Home</li>
<li>Portfolio</li>
<li>Who Are We?</li>
<li>Our Services</li>
<li>Features</li>
<li>Keep in Touch</li>
</ul>
</div>
Also I noticed on the page you have your css defined before the reset.css is called in. That's usually bad practice you might want to make sure reset.css is always the very first css file pulled in. It doesn't appear to have affected the page much but sometimes you'll get weird results doing that.
I made a jsfiddle of the results here: http://jsfiddle.net/RNsFw/2/
the waypoints plugin isn't needed anymore I think. I didn't change the fancybox or validation stuff because i'm not sure what those are doing and it wasn't really part of your issue.
I tested it in firefox and Chrome. Let me know if you have questions :)

http://jsfiddle.net/vCgy8/9/
This removes the dependency on scrollTo, and the waypoints plugin.
$('body').click(function(event)
{
if(event.target.nodeName.toLowerCase() == 'a')
{
var op = $(event.target);
var id = op.attr('href');
if(id.indexOf('#') == 0)
{
destination = $(id).offset().top;
$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, 1000, function() {
var hash = id.split('#')[1];
window.location.hash = hash;
});
}
return false;
}
});
$(window).scroll(function (event){
makeActive();
});
function makeActive(){
var y = $(this).scrollTop();
if(y!==0){
$('.page_name').each(function(){
var curPos = parseInt($(this).offset().top - y);
if(curPos <= 0){
var op = $('#navigation a[href = "#'+$(this).attr('id')+'"]');
$("#navigation a").removeClass("active");
op.addClass('active');
}
});
}else{
$("#navigation a").removeClass("active");
$("#navigation a:first").addClass('active');
}
}
makeActive();

This may be completely unrelated, but I had a similar problem yesterday - where, in the callback of an event handler, jQuery operations weren't being performed in that scope but if you threw the code into something like:
setTimeout(function() {
$(selector).addClass('foo');
}, 0);
it would work - similar to how $.animate() functions (ish) if you call $(selector).stop().animate() without the queue param being false, eg:
$(selector).stop();
$(selector).animate({ foo }, { no queue:false here });
// ^ fail
$(selector).stop();
setTimeout(function() {
$(selector).animate({ foo }, { no queue:false here either });
}, 0);
// ^ success
The problem, completely unrelated to the above example though similar in behavior/functional hack, turned out to be the method of binding - in my case I had been using $.bind() - but then I refactored this to use $.delegate() ($.live() would work also) and it functioned as expected.
Again, not sure if this related, but figured I'd pass that along just in case. Unsure if it's a bug or just me not properly understanding some of the subtler parts of jQuery.

The problem is not in your js code, but in your css/page layout.
Or maybe the problem is that you are using the waypoint plugin and you might not want to for this particular page. (As you will see you also have trouble hitting the "Home" waypoint again once you have left it, because of the offset you use.)
The thing is, the waypoint plugin won't trigger until the target element you are scrolling to is in the very top of the browser window, with respect to the offset that is. "Keep in touch" will never get to the top unless your browser window is small enough that the "keep in touch" section takes up the entire browser window (minus the offset).
You can see it visualized here:

Related

Remove transparency on menu drop down Javascript

I've been trying to implement a feature that removes the transparency of the dropdown menu on my website so that it is actually readable for visitors.
The code I am currently using, which removes transparency on scroll but not on drop down is:
$(document).ready(function(){
var stoptransparency = 100; // when to stop the transparent menu
var lastScrollTop = 0, delta = 5;
$(this).scrollTop(0);
$(window).on('scroll load resize', function() {
var position = $(this).scrollTop();
if(position > stoptransparency) {
$('#transmenu').removeClass('transparency');
} else {
$('#transmenu').addClass('transparency');
}
lastScrollTop = position;
});
$('#transmenu .dropdown').on('show.bs.dropdown', function() {
$(this).find('.dropdown-menu').first().stop(true, true).slideDown(300);
});
$('#transmenu .dropdown').on('hide.bs.dropdown', function() {
$(this).find('.dropdown-menu').first().stop(true, true).slideUp(300);
});
});
I tried changing it to this (and variations of this) but can't seem to get it to work:
$(document).ready(function(){
var stoptransparency = 100; // when to stop the transparent menu
var lastScrollTop = 0, delta = 5;
$(this).scrollTop(0);
$(window).on('scroll load resize', function() {
var position = $(this).scrollTop();
if(position > stoptransparency) {
$('#transmenu').removeClass('transparency');
} else {
$('#transmenu').addClass('transparency');
}
lastScrollTop = position;
});
$('#transmenu .dropdown').on('show.bs.dropdown', function() {
$(this).find('.dropdown-menu').first().stop(true, true).slideDown(300);
$('#transmenu').removeClass('transparency');
});
$('#transmenu .dropdown').on('hide.bs.dropdown', function() {
$(this).find('.dropdown-menu').first().stop(true, true).slideUp(300);
$('#transmenu').addClass('transparency');
});
});
Any help would be greatly appreciated!
Thanks!
Without the html that this is hooking into it's a bit difficult to answer your question.
But given the fact that scrolling gets the job done, the only element I can see that could be preventing the functionality you want is that your selector to add show event handler is either selecting nothing in particular or an element in the DOM that is not the bootstrap dropdown element that triggers 'show.bs.dropdown', which is my reasoning for the first statement.
You can try the following debug code to verify:
// Should log to console with 'selected' if selector works alternatively 'not selected'
console.log($('#transmenu .dropdown').length > 0 ? 'selected' : 'not selected');
// Log to console when show event triggered
$('#transmenu .dropdown').on('show.bs.dropdown', function() {
console.log('triggered');
});
Hope that helps you find a solution. Happy coding!
see the documentation at http://api.jquery.com/on/ and it should become obvious why your fancy named events are never being triggered (without defining any event namespace in the first place).
$('#transmenu .dropdown')
.on('show', function() {})
.on('hide', function() {});
the DOM selector also might be #transmenu.dropdown instead of #transmenu .dropdown (depending if id and class attributes are present on the DOM node to select - or if one selects the parent node by id and there is/are nested node/s with a class attribute present).

JQuery trigger click event when page load

In my site when URL is something like this: www.example.com/question/#comment23
i want to scroll to this and i use this code:
if (window.location.hash) {
var elem = $(window.location.hash);
var elemId = $(elem).attr('id')
var top = $('#' + elemId).offset().top - 60;
var moreCmntElm = $('#' + elemId).closest('.comment-wrp').siblings('.create-comment-wrp').children('.moreCommnets');
$('html, body').animate({
scrollTop: top
}, 1600, 'easeInOutQuart')
if (moreCmntElm.css('display') == "none") {
moreCmntElmFunc(moreCmntElm.children('button')[0])
}
}
But its possible the comment is hidden display:none (like stackoverflow when a question has a lot of comment), in this case i want the show more comment button event to be trigger.
This function show other comments:
function moreCmntElmFunc($this) {
$this.closest('.other-user-comments-wrp').children().show('blind', 'fast');
$this.css('display', 'none');
$this.parent().css('display', 'none');
}
But code work properly and other comments are displayed.
My problem is i get an error and else other JS operation doesn't work.
$this.closest(...).children is not a function
Since children() is a jQuery function and moreCmntElm.children('button')[0] returns underlying DOM element and they can't execute the jQuery function. Thus you are getting the error
Use .eq()
moreCmntElmFunc(moreCmntElm.children('button').eq(0)); //.first() can also be used
instead of
moreCmntElmFunc(moreCmntElm.children('button')[0]);

Bootstrap: scrollspy doesn't work after I've added smooth scrolling

I'm building a site using Twitter Bootstrap, and I got the scrollspy to work, using the below javascript:
$('body').scrollspy({ target: '.navbar' })
But it stopped working for me, after I add the script to enable smooth scrolling:
<script type="text/javascript">
$(document).ready(function() {
// navigation click actions
$('.scroll-link').on('click', function(event){
event.preventDefault();
var sectionID = $(this).attr("data-id");
scrollToID('#' + sectionID, 750);
});
// scroll to top action
$('.scroll-top').on('click', function(event) {
event.preventDefault();
$('html, body').animate({scrollTop:0}, 'slow');
});
// mobile nav toggle
$('.nav-toggle').on('click', function (event) {
event.preventDefault();
$('#bs-example-navbar-collapse-1').toggleClass("open");
});
});
// scroll function
function scrollToID(id, speed){
var offSet = 70;
var targetOffset = $(id).offset().top - offSet;
var mainNav = $('#bs-example-navbar-collapse-1');
$('html,body').animate({scrollTop:targetOffset}, speed);
if (mainNav.hasClass("open")) {
mainNav.css("height", "1px").removeClass("in").addClass("collapse");
mainNav.removeClass("open");
}
}
if (typeof console === "undefined") {
console = {
log: function() { }
};
}
</script>
I'm thinking I must have added the scrollspy in an incorrect position. I have very little knowledge of javascript. If someone can point me the way to inserting it in the correct order/space/line, that would be great!
Thanks in advance!
You may want to use a third party plugin such as jquery.localScroll (which relies on jquery.scrollTo). It provides great smooth scrolling and is easy to implement. A lot easier than reimplementing the wheel.
https://github.com/flesler/jquery.localScroll

jQuery: Hide element after scrollTop value is passed

I want to hide a div once my slider passes a scrollTop() value of 200px. I've looked at this article and tried using it as a template for what I want. I have the following code, but its not hiding the element. Live site
function removeArrow() {
$(window).scroll(function() {
if($('.portfolio-sliders:first-child').scrollTop() > 100) { //use `this`, not `document`
$('.scrl-dwn').css({
'display': 'none'
});
}
});
}
UPDATE
I've updated by code:
function removeArrow() {
$(window).scroll(function() {
var slider = $('.portfolio-sliders:first-child').position.top;
if(slider >= 10) {
$('.scrl-dwn').hide();
}
});
}
which should work, but its not...
Position is a function, not a property. You need to call the function with ():
var slider = $('.portfolio-sliders:first-child').position().top;
Replace your whole removeArrow function with this code.
(If you open your live site, and run this in the console, you can see it's working).
The scroll event never fired, so I handled theese mousewheel events instead.
$(window).bind('DOMMouseScroll mousewheel', function() {
var div = $(".portfolio-sliders:first-child"),
top = div.position().top,
display = top < 400 ? 'none' : '';
$('.scrl-dwn').css({ 'display': display });
});
Use This :
$(window).scroll(function(){
if ($(window).scrollTop() > 660)
{
$(".Left-Section").css("position", "fixed");
$(".Center-Content").css("margin-top", "0");
$(".Right-Nav img").css("transform", "rotate(360deg)");
}
;)

Javascript or jQuery slide to element

When a user clicks on the "Contact Me" button, i want the screen to slide to the #contact element, however cannot figure out how to do it. I've tried various different snippets of code and tried to tailor it to my needs, but nothing seems to work.
The site is here; http://dombracher.com/
Simply want the screen to slide to the div mentioned above, rather than quickly snap to it.
Thanks in advance.
$(document).ready(function() {
$("a[href^='#']").anchorAnimate()
});
jQuery.fn.anchorAnimate = function(settings) {
settings = jQuery.extend({
speed : 1100
}, settings);
return this.each(function(){
var caller = this
$(caller).click(function (event) {
event.preventDefault()
var locationHref = window.location.href
var elementClick = $(caller).attr("href")
var destination = $(elementClick).offset().top;
$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() {
window.location.hash = elementClick
});
return false;
})
})
}
You can animate window scroll by yourself
$(".menu2").click(function(){
$(document.body).animate({
"scrollTop": $("#contact").offset().top
}, 2000, "swing"); // animation time and easing
return false; // preventing default jump
});
Fiddle: http://jsfiddle.net/M8JE2/
Or use jquery plugin like http://flesler.blogspot.com/2007/10/jquerylocalscroll-10.html to make any/all local links work with animation.
Here it is , scrolls to the bottom of the page since your contact form is there:
jQuery(function () {
jQuery('#nav1 li.menu2').click(function (e) {
jQuery("html, body").stop().animate({
scrollTop: jQuery(document).height()
}, 1000);
e.preventDefault();
return false;
});
});

Categories