Change "selected" on scroll in page - javascript

I've been trying to get the automatic update on my navbar but i cant get it to work.
Here is my code: http://pastebin.com/YTHaBD0i
<div id="header">
<ul class="nav-list">
<li class="download selected">Download</li>
<li class="features">Features</li>
<li class="method">Method</li>
<li class="purchase">Purchase</li>
</ul>
</div>
<div id="footer">yey productions © 2016</div>
<div id="fullpage">
<div class="section " id="section0">
<div class="intro">
<h1>Download</h1>
<p>Lorem Ipsum</p>
</div>
</div>
<div class="section" id="section1">
<div class="slide" id="slide1">
<div class="intro">
<h1>Features</h1>
<p>Cheese.</p>
</div>
</div>
<div class="slide" id="slide2">
<h1>Cheese2</h1>
</div>
</div>
<div class="section" id="section2">
<div class="intro">
<h1>Yey</h1>
</div>
</div>
<div class="section" id="section3">
<div class="intro">
<h1>Yey2</h1>
</div>
</div>
</div>
Help would be much appreciated!
Greetz,

Assuming you are using jQuery, you will need a function that fires every time you scroll.
From there, you need to detect which elements are in view.
Once you know which elements are in view, clear any currently active elements with the .selected class, then choose which one you want to be .selected and add the .selected class.
Edit for more detail:
Below is a pure JavaScript solution, which I found here. This should be close to a drop-in solution!:
(function() {
'use strict';
var section = document.querySelectorAll(".section");
var sections = {};
var i = 0;
Array.prototype.forEach.call(section, function(e) {
sections[e.id] = e.offsetTop;
});
window.onscroll = function() {
var scrollPosition = document.documentElement.scrollTop || document.body.scrollTop;
for (i in sections) {
if (sections[i] <= scrollPosition) {
document.querySelector('.selected').setAttribute('class', ' ');
document.querySelector('a[href*=' + i + ']').setAttribute('class', 'selected');
}
}
};
})();

Related

Simplify Javascript object

I am using object-oriented javascript to show/hide 'views' on click of the nav link and also on a button that is used to go to the next view. I feel like this can definitely be simplified but I am not sure what the best way to do this is. My html is as follows:
<div id="sidebar">
<svg width="261" height="70"><use xlink:href="#logo"></use></svg>
<nav>
<ol>
<li><span>1</span>Run your business</li>
<li><span>2</span>Let us work for you</li>
<li><span>3</span>Check your books</li>
</ol>
</nav>
<a class="progress-btn main-btn visible" href="#">Start the demo</a>
<a class="progress-btn main-btn" href="#">Next</a>
<a class="progress-btn main-btn" href="#">Next</a>
<a class="progress-btn main-btn" href="#">30-day free trial</a>
</div><!--end sidebar-->
<div id="content">
<div class="page page1">
<h2>Page 1</h2>
</div><!--end page1-->
<div class="page page2">
<h2>Page 2</h2>
</div><!--end page2-->
<div class="page page3">
<h2>Page 3</h2>
</div><!--end page3-->
<div class="page page4">
<h2>Page 4</h2>
</div><!--end page4-->
</div><!--end content-->
And my object looks like this:
View = {
page: '.page',
mainLink: '#sidebar li a',
progressButton: '.progress-btn',
init: function() {
$(this.mainLink).click(this.showView.bind(this));
$(this.mainLink).click(this.activeNav.bind(this));
$(this.progressButton).click(this.sidebarButton.bind(this));
},
showView: function(e) {
e.preventDefault();
var target = $(e.target),
targetIndex = target.index(this.mainLink),
pageToTarget = targetIndex + 2;
$(this.page).removeClass("current").fadeOut('fast').promise().done(function() {
$('.page' + pageToTarget).fadeIn().addClass("current");
});
},
activeNav: function(e) {
$(this.mainLink).removeClass("active");
e.preventDefault();
$(e.target).addClass("active");
var targetIndex = $(e.target).index(this.mainLink)
$(".progress-btn").removeClass("visible");
$(".progress-btn").eq(targetIndex + 1).addClass("visible");
},
sidebarButton: function(e) {
e.preventDefault();
var target = $(e.target);
targetIndex = target.index(this.progressButton);
pageToTarget = targetIndex + 2;
if (target.text() == "30-day free trial") {
window.open("http://google.com");
} else {
target.removeClass("visible");
target.next().addClass("visible");
$(this.page).removeClass("current").fadeOut('fast').promise().done(function() {
$('.page' + pageToTarget).fadeIn().addClass("current");
});
$(this.mainLink).removeClass("active");
$("#sidebar li a").eq(targetIndex).addClass("active");
}
console.log(targetIndex);
// pageRoute(targetIndex);
}
}
View.init();
Here is a fiddle https://jsfiddle.net/rsgLbgg3/4/. How can I simplify this to work with both the nav and the button without being so repetitive.
Just learning to learn a little. Thanks in advance!

Jquery click only work once on toggle

I am using the following script to show a different background depending on the state of the div.
When it is not expanded it shows the "plus (+)" sign, while when is expanded it does not have background image (does not shows anything).
The problem there is that only work once, and I dont know why.
Here's the code:
EDIT (added HTML)!
HTML:
<body>
<section>
<div class="wrapper wf">
<ul id="Parks" class="just">
<!--------------- PRODUCT -->
<li class="mix" href="#therapy_vital" >
<div class="meta name">
<div class="img_wrapper">
<img src="images/spa/masaje/.jpg" onload="imgLoaded(this)"/>
</div>
<div class="titles">
<h2>TITLE</h2>
</div>
</div>
<!-- Expand -->
<div href="#therapy_vital" class="nav-toggle"></div>
<div id="therapy_vital" style="display:none">
<article class="ac-small">
SUBCONTENT<br><br><br><br><br><br><br><br><br><br><br><br>
</article>
</div>
</li>
<!--------------- PRODUCT -->
<li class="mix" href="#therapy_natur" >
<div class="meta name">
<div class="img_wrapper">
<img src="images/spa/masaje/.jpg" onload="imgLoaded(this)"/>
</div>
<div class="titles">
<h2>TITLE</h2>
</div>
</div>
<!-- Expand -->
<div href="#therapy_natur" class="nav-toggle"></div>
<div id="therapy_natur" style="display:none">
<article class="ac-small">
SUBCONTENT<br><br><br><br><br><br><br><br><br><br><br><br>
</article>
</div>
</li>
</ul>
</div>
</section>
</body>
JS:
$(document).ready(function() {
$('.meta').click(function() {
$(this).css('background', 'none');
});
$('.mix').click(function() {
var collapse_content_selector = $(this).attr('href');
var toggle = $(this);
$('.meta').click(function() {
$(this).css('background', 'url(images/arrow_down.png) no-repeat scroll 95% 97% transparent');
});
$(collapse_content_selector).toggle(function() {});
});
});
(The .mix value makes the Div expands, and the .meta class switch to different background).
Any clue?
EDIT2 (Live example)
http://anubisfiles.com/test/test.html
(Due I am not really familiar with jsFiddle, I prefer to show you it hosted on a website).
Thanks!
Use on function to bind events,
$('element').on('click', function() {
});
$('.mix').click(function() {
var collapse_content_selector = $(this).attr('href');
var toggle = $(this);
$(this).find('.meta').css('background', 'url(images/arrow_down.png) no-repeat scroll 95% 97% transparent');
$(collapse_content_selector).toggle(function() {});
});
Try this

JavaScript function fires twice on click

I am building a web app at the moment, and I have a strange problem, I have the following HTML,
It has code that is similar to this format:
<article class="item">
<header class="active">
</header>
<div class="item_content">
<div class="item-tabs">
<ul>
<li>Description<li>
<li>Tasks</li> <!-- THERE IS A CLICK EVENT ON THIS -->
</ul>
<div class="tab-content item-description">Description</div>
<div class="tab-content item-tasks">Tasks</div>
</div>
<article class="item">
<header class="active">
</header>
<div class="item_content">
<div class="item-tabs">
<ul>
<li>Description<li>
<li>Tasks</li> <!-- THERE IS A CLICK EVENT ON THIS -->
</ul>
<div class="tab-content item-description">Description</div>
<div class="tab-content item-tasks">Tasks</div>
</div>
</div>
</article>
</article>
The first class="tab-link" triggers the JavaScript below once, but the second `class="tab-link" triggers the JavaScript below twice. Is there any reason for this?
itemTab: function(e) {
var clicked = $(e.currentTarget),
clickedTab = clicked.data("tab");
if(clicked.closest(".item-tabs").find("." + clickedTab).css("display") == "block")
{
clicked.closest(".item-tabs").find(".tab-content.active").slideUp(500, function(){
clicked.closest(".item-tabs").find(".tab-content.active").removeClass("active");
});
clicked.closest(".item-tabs").find(".close").css("visibility", "hidden");
clicked.closest(".item-tabs").find("li.active").removeClass("active");
}
else
{
clicked.closest(".item-tabs").find(".tab-content.active").removeClass("active");
clicked.parent().addClass("active");
clicked.closest(".item-tabs").find("." + clickedTab).addClass("active");
clicked.closest(".item-tabs").find(".close").css("visibility", "visible");
}
e.preventDefault();
//stop();
},

Generate link based on data attributes

I am trying to write a little jQuery script that checks a set of div's to see if they have a data-name attribute. For the ones that have a data-name, it will create a link. The href of that link should be the name of the data-value plus contain the file extension (eg. .txt).
Everything seems to work OK except when I try to add the data value onto the link. The ultimate result of this script is to output something like this for each of those div's:
<p class="data-link">Edit
Below is my script. I have identified that area that I am having issue with.
var dataNameWrappers = $("div#desktopSidebar div[data-name]");
dataNameWrappers.each(function() {
var dataNameWrappers_action = "" + $(this).attr("data-name");
$(this).prepend("<p class='edit-link'><a>Edit</a></p>");
var dataNameWrapperEditLink = $("div#desktopSidebar p.edit-link a");
dataNameWrapperEditLink.each(function() {
$(this).attr('href', <<stuck_here>>);
});
});
Any help will be great.
Thanks
As requested, here is my sidebar HTMl structure
<div id="desktopSidebar">
<div class="sidebar userbox">
<h3 class="sidebarheader"> Welcome {{username}}}</h3>
</div>
<div data-name="social_media_sitewide" class="sidebar socialmedia">
<h3 class="sidebarheader">Follow Tennis-Chat</h3>
</div>
<div data-name="site_promotions" class="sidebar promotions">
<h3 class="sidebarheader">Current Promotions</h3>
</div>
<div data-name="livescores" class="sidebar Livescores">
<h3 class="sidebarheader">Live Scores</h3>
</div>
<div class="sidebar tournaments">
<h3 class="sidebarheader">Tournaments</h3>
</div>
<div data-name="featured-profiles" class="sidebar profiles">
<h3 class="sidebarheader">Today's Profile: {{featured_profile_name}}</h3>
</div>
<div data-name="side_advertisment" class="sidebar Advertisement">
<h3 class="sidebarheader">Advertisement</h3>
</div>
<div class="sidebar Headlines">
<h3 class="sidebarheader">Tennis-Chat Headlines</h3>
</div>
<div class="sidebar mostrecent" id="mostRecentTopics">
<h3 class="sidebarheader">Most Recent Posts</h3>
</div>
</div>
I don't know why you are using a second loop to add the HREFs when you already have everything you need.
Working fiddle here: http://jsfiddle.net/Q4j8S/.
HTML:
<div id="desktopSidebar">
<div class="sidebar userbox">
<h3 class="sidebarheader"> Welcome {{username}}}</h3>
</div>
<div data-name="social_media_sitewide" class="sidebar socialmedia">
<h3 class="sidebarheader">Follow Tennis-Chat</h3>
</div>
<div data-name="site_promotions" class="sidebar promotions">
<h3 class="sidebarheader">Current Promotions</h3>
</div>
<div data-name="livescores" class="sidebar Livescores">
<h3 class="sidebarheader">Live Scores</h3>
</div>
<div class="sidebar tournaments">
<h3 class="sidebarheader">Tournaments</h3>
</div>
<div data-name="featured-profiles" class="sidebar profiles">
<h3 class="sidebarheader">Today's Profile: {{featured_profile_name}}</h3>
</div>
<div data-name="side_advertisment" class="sidebar Advertisement">
<h3 class="sidebarheader">Advertisement</h3>
</div>
<div class="sidebar Headlines">
<h3 class="sidebarheader">Tennis-Chat Headlines</h3>
</div>
<div class="sidebar mostrecent" id="mostRecentTopics">
<h3 class="sidebarheader">Most Recent Posts</h3>
</div>
</div>
JavaScript:
var dataNameWrappers = $("div#desktopSidebar div[data-name]");
dataNameWrappers.each(function() {
var dataNameWrappers_action = $(this).attr("data-name");
console.log('data-name ' + dataNameWrappers_action);
$(this).prepend('<p class="edit-link">Edit</p>');
/* Don't need this
var dataNameWrapperEditLink = $("div#desktopSidebar p.edit-link a");
dataNameWrapperEditLink.each(function() {
$(this).attr('href', dataNameWrappers_action);
});
*/
});
Instead of iterating through the a tags after you do the prepend, it may be better to make the HTML fragment with the desired href attribute.
Here is the code that accomplishes that:
$('#desktopSidebar .sidebar[data-name]').each(function(index, el){
var href = $(el).attr('data-name') + ".txt";
$(el).prepend('<p class="edit-link">Edit');
});

Toggle Multiple divs for show hide

ok, So I have multiple divs(7) which I want to toggle for show hide. If one div is open rest should hide and when I open a new div the others should hide. I have been able to accomplish this with the below piece of jquery
function showDivs() {
$(".head").click(function() {
$(".Content").hide();
$(this).next().fadeIn("slow");
})
}
where .head is the header for each div and .Content is the class for divs. I have got it working perfectly, by calling showDivs() from .head() Now the question is that on the left hand side of my page, I have ul li set. I have 7 li items, that correspond to 7 divs. I mean on click of first li the corresponding div should open up and the others should hide, and on click of 2nd li the 2nd div should open up and the others hide.
Does anybody have an idea how to make these divs show hide on the action of li items on left. I know I have to pass parameters for showDivs(), but don't know how?
help is appreciated
I believe this is where .index() comes into play:
$(function() {
$('ul li').each(function() {
$(this).click(function(e) {
var i = $(this).index();
$('div').hide();
$('div:eq('+i+')').show();
});
});
});
That's a pretty basic markup but I'm sure you can work out how to get it working with your code. Hope I helped!
http://jsfiddle.net/Z3Hj7/
EDIT: After having seen your fiddle I think i worked out exactly what you want:
$(function() {
$('ul li').each(function() {
$(this).click(function(e){
e.preventDefault();
var i = $(this).index();
$('.content').hide();
$('.head:eq('+i+')').next().show();
});
});
});
Take a look at the fiddle: http://jsfiddle.net/DTcGD/25/
If I understand your HTML structure correctly, it looks about like this:
<!-- The list... -->
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>
<!-- The divs -- note I've assumed there's a container... -->
<div id="container">
<div class="head">Header One</div>
<div class="Content">Content One</div>
<div class="head">Header Two</div>
<div class="Content">Content Two</div>
<div class="head">Header Three</div>
<div class="Content">Content Three</div>
<div class="head">Header Four</div>
<div class="Content">Content Four</div>
</div>
...only with seven items rather than four.
If so, this would do it (live copy):
jQuery(function($) {
$(".Content").hide();
$("li").click(function() {
showDivs($("#container div.head:eq(" + $(this).index() + ")"));
});
$(".head").click(function() {
showDivs($(this));
});
function showDivs(head) {
$(".Content").hide();
head.next().fadeIn("slow");
}
});
There, I'm relating the list to the headers implicitly, by where they are in their container. So the first li relates to the first div with class="head", the second to the second, etc. I'm doing that by using index to know which li was clicked, and then looking up the related div.head using :eq.
Doing it structurally rather than with id values makes it much easier to maintain. Alternately, though, you could do it by giving each li a data-div attribute with the value of the id of the related div:
<ul>
<li data-div="h1">One</li>
<li data-div="h2">Two</li>
<li data-div="h3">Three</li>
<li data-div="h4">Four</li>
</ul>
<div id="container">
<div id="h1" class="head">Header One</div>
<div class="Content">Content One</div>
<div id="h2" class="head">Header Two</div>
<div class="Content">Content Two</div>
<div id="h3" class="head">Header Three</div>
<div class="Content">Content Three</div>
<div id="h4" class="head">Header Four</div>
<div class="Content">Content Four</div>
</div>
Then (live copy):
jQuery(function($) {
$(".Content").hide();
$("li").click(function() {
showDivs($("#" + $(this).attr("data-div")));
});
$(".head").click(function() {
showDivs($(this));
});
function showDivs(head) {
$(".Content").hide();
head.next().fadeIn("slow");
}
});
data-* attributes are valid as of HTML5, but all browsers support them right now. (The data-* thing is an attempt to codify and reign in people's use of invalid attributes, by giving them a valid way to do it without conflicting with future additions to the spec.)
How about asigning an id to each list item and a corosponding id to each item container. So your list items get an id of "item01".."item07" and your content containers gets id of "item01c".."item07c". Then you can do somehing like this:
$("li").click(function() {
showDivs($(this).attr("id"));
})
function showDivs(callerId) {
$(".content").hide();
$(".content", "#" + callerId + "c").fadeIn();
}
Working example can be seen here: http://jsfiddle.net/ECbkd/5/1
If you want to use .index() as suggested by someone earlier, then I belive this would be the simplest approach (check it out here http://jsfiddle.net/ECbkd/7/):
$("li").click(function() {
$(".content").hide();
$('.item').eq($(this).index()).children('.content').fadeIn();
})
You could add this to be able to show content when clickin on header also:
$("h2", ".container").click(function() {
$(".content").hide();
$(this).parent().children('.content').fadeIn();
})
* EDIT START *
To let content toggle on click at header use this:
$("h2", ".container").click(function() {
$(".content").not($(this).parent().children('.content')).hide();
$(this).parent().children('.content').toggle();
})
Updated code here
http://jsfiddle.net/ECbkd/8/
* EDIT END *
This is based on html like this:
<ul>
<li>Item 01</li>
<li>Item 02</li>
<li>Item 03</li>
<li>Item 04</li>
<li>Item 05</li>
<li>Item 06</li>
<li>Item 07</li>
</ul>
<div class='container'>
<div class='item'>
<h2>Header 1</h2>
<div class='content'>Content 1</div>
</div>
<div class='item'>
<h2>Header 2</h2>
<div class='content'>Content 2</div>
</div>
<div class='item'>
<h2>Header 3</h2>
<div class='content'>Content 3</div>
</div>
<div class='item'>
<h2>Header 4</h2>
<div class='content'>Content 4</div>
</div>
<div class='item'>
<h2>Header 5</h2>
<div class='content'>Content 5</div>
</div>
<div class='item'>
<h2>Header 6</h2>
<div class='content'>Content 6</div>
</div>
<div class='item'>
<h2>Header 7</h2>
<div class='content'>Content 7</div>
</div>
</div>
you can show and hide multiple divs by using this simple method
function w3_open() {
document.getElementById("id01").style.display =
"block"; document.getElementById("id02").style.display = "block"
}
make sure that you are using w3.css
<button onclick="w3_open()" class="w3-button w3-opacity w3-black">Yesterday</button>
<div id="id01" class="w3-panel w3-white w3-card w3-display-container">
<span onclick="document.getElementById('id01').style.display='none'"
class="w3-button w3-display-topright">×</span>
<p class="w3-text-blue"><b>email.zip</b></p>
<p>https://www.w3schools.com/lib/email.zip</p>
<p class="w3-text-blue">Show in folder</p>
</div>
<div id="id02" class="test w3-panel w3-white w3-card w3-display-
container">
<span onclick="document.getElementById('id02').style.display='none'"
class="w3-button w3-display-topright">×</span>
<p class="w3-text-blue"><b>email.zip</b></p>
<p>https://www.w3schools.com/lib/email.zip</p>
<p class="w3-text-blue">Show in folder</p>
</div>
If you give the li's and the corresponding divs the same class, then you can say something like
function showDivs() {
$("li").click(function() {
$(".Content").hide();
clickedID = $(this).attr("class");
$('div#'+clickedID).fadeIn("slow");
})
}

Categories

Resources