How to get infinite scroll to work? - javascript

I'm trying to get this infinite load script to work in my project.
Here's my HTML:
<!-- Contents -->
<div id="page-container">
<div id="scroller">
<div id="page_1" class="pagina"></div>
<div id="page_2" class="pagina"></div>
<div id="page_3" class="pagina"></div>
<div id="page_4" class="pagina"></div>
<div id="page_5" class="pagina"></div>
<div id="page_6" class="pagina"></div>
</div>
</div>
<div id="pages-to-load">
<div id="page_7" class="pagina"></div>
...
<div id="page_25" class="pagina"></div>
</div>
And here's the script:
function scrollalert(){
var pages = document.getElementById("scroller").getElementsByTagName("div");
var currentPageId = pages[pages.length - 1];
//console.log("currentPageId is: "+currentPageId);
var scrollbox = document.querySelector('#page-container');
var scrolltop = $(window).scrollTop();
var scrollheight = scrollbox.scrollHeight;
var windowheight = $(window).height();
var scrolloffset=20;
console.log(scrolltop);
console.log(scrollheight);
console.log(windowheight);
console.log(scrollheight-(windowheight+scrolloffset));
if(scrolltop>=(scrollheight-(windowheight+scrolloffset))) {
//fetch new items
console.log("loading more pages");
(function() {
alert('test');
var i;
var pagesToLoad = $("#pages-to-load > div").size();
for (i = 0; i < pagesToLoad; i++) {
console.log(pagesToLoad[i].id);
$.get(pagesToLoad[i].id, function(newitems){
alert('get new page');
$('#scroller').append(newitems);
updatestatus();
})
};
})();
};
}
Whatever I try, I can't seem to load and append my new pages. Also when scrolling down, my scrollTop and scrollHeight don't change. I'm sure I'm missing something obvious here. Also my pages-to-load is undefined?

Here is one infinite-scroll script of mine using JQuery which works:
Html:
<html>
<head>
<title>Scroll Troll Page</title>
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
</head>
<body>
<div id="scrollbox">
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
</div>
</body>
<script type="text/javascript">
$(window).scroll(function () {
//- 10 = desired pixel distance from the bottom of the page while scrolling)
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
var box = $("#scrollbox");
//Just append some content here
box.html(box.html() + "<br /><br /><br /><br /><br /><br /><br />");
}
});
</script>
in Line:
box.html(box.html + "Place content to expand here");
You can add the content that should be added to your container when reaching the bottom of the page while scrolling.
Working jsFiddle:
http://jsfiddle.net/MdrJ4/3/

I think we should rely on intersectionObserver instead of the onScroll event. I have put together an article on medium here explaining the performance gains of the two approaches
you only need vanilla js

i have a problem for using endless scrolling, so i wrote a library and solved my problem. i think this library may help you for this problem.
use this library as easy way to implement infinite scrolling :
https://github.com/hamedtaheri32/infinite-scrolling
example :
<script>
$(document).ready(function(){
$(document).infiniteJscroll({
offset:0,
topOfPage:function(){
console.log('Scrolled to Page Top');
},
bottomOfPage:function(){
console.log('Scrolled to Page Bottom');
addContent();
},
pageInit:function(){
console.log('Initialize page');
addContent();
}
});
});
//This method used for simulate loading data from server. replace it with AJAX loading method.
function addContent() {
var c = '';
for (var i = 0; i < 10; i++) {
c += '<a class="box"></a>';
}
$("#post").append(c);
}
</script>
features :
detect page top
detect page bottom
can use offset for detect page bottom
have page initialize method
ability for mix with AJAX loading page

can use below script
window.onscroll = function (ev) {
let scrollHeight = Math.max(
document.body.scrollHeight, document.documentElement.scrollHeight,
document.body.offsetHeight, document.documentElement.offsetHeight,
document.body.clientHeight, document.documentElement.clientHeight
);
let currentScrollHeight = window.innerHeight + window.scrollY;
if ((scrollHeight - currentScrollHeight) < 200) {
// your statement
}
};
full example in jsfiddle

This is what I did: (Please correct me if I'm wrong)
$(document).ready(() => {
var page = 1;
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
page++;
if (page == 2) {
$('#div2').removeClass('hide');
}
if (page == 3) {
$('#div3').removeClass('hide');
}
if (page == 4) {
$('#div4').removeClass('hide');
page = 1;
}
}
});
});
.page {
width: 100%;
background-color: black;
color: white;
height: 100vh;
border-top: 1px solid white;
}
.hide {
display: none;
}
body {
margin: 0px;
padding: 0px;
}
<!DOCTYPE html>
<html>
<head>
<title>Infinite Scroll</title>
<link href='css/bootstrap.css' ref='stylesheet'>
</head>
<body>
<div id='div' class='page'>
<h1>Page 1</h1>
</div>
<div id='div2' class="page hide">
<h1>Page 2</h1>
</div>
<div id='div3' class="page hide">
<h1>Page 3</h1>
</div>
<div id='div4' class="page hide">
<h1>Page 4</h1>
</div>
<script src='js/jquery.min.js'></script>
<script src='js/popper.min.js'></script>
<script src='js/bootstrap.min.js'></script>
<script src='js/myjquery.js'></script>
</body>
</html>

// check if scrolling near to bootom of page , load more photos
window.addEventListener('scroll',()=>{
if(window.innerHeight+window.scrollY>=document.body.offsetHeight-100){
//your logic or function
}
});

Related

Javascript Help - Timer (Not Counting Up) and Alert Box (Not Showing Up)

I am new to JavaScript and HTML but am slowly getting HTML but JavaScript I am struggling with. I am stuck on a problem that is having me have a counter start when I click the Start Quiz button. I am also having a problem with an Alert Box showing up when I click the Submit Answers button. I am not looking for someone to give me the answer but some guidance would be helpful.
<head>
<meta charset="UTF-8" />
<title>Trivia Quiz: Movies</title>
<script src="modernizr-1.5.js" type="text/javascript" ></script>
<link href="quiz.css" rel="stylesheet" type="text/css" />
<script src="functions.js" type="text/javascript" ></script>
<script type="text/javascript">
var seconds = "0";
var clockID;
</script>
<script type="text/javascript">
function runClock() {
seconds++;
document.getElementByID('quizclock')value=seconds;
}
</script>
<script type="text/javascript">
function startClock() {
showQuiz();
clockId=setInterval ("runClock()", 1000);
}
</script>
<script type="text/javascript">
function stopClock() {
clearInterval (clockId);
correctAns = gradeQuiz();
window.alert("You have" + correctAns + "correct of 5 in" + timer + "seconds");
}
</script>
</head>
<body onload="resetQuiz()">
<form id="quiz" name="quiz" action="">
<header>
<img src="tlogo.png" alt="Online Trivia" />
<nav class="horizontal">
<ul>
<li>Top Scores</li>
<li>Submit a Quiz</li>
<li>Quiz Bowl</li>
<li>Your Account</li>
</ul>
</nav>
</header>
<nav class="vertical">
<h1>Categories</h1>
<ul>
<li>Arts</li>
<li>Books</li>
<li>Culture</li>
<li>Geography</li>
<li>History</li>
<li>Movies</li>
<li>Music</li>
<li>People</li>
<li>Random</li>
<li>Science</li>
<li>Sports</li>
<li>Television</li>
</ul>
</nav>
<section id="main">
<h1>Movie Trivia</h1>
<p>
All of our trivia quizzes are scored on the number of correct
answers and the time required to submit those answers.
</p>
<p>
To start the quiz, click the <b>Start Quiz</b> button below,
which will reveal the first page of quiz questions and start
the timer. When you have completed the questions, click
the <b>Submit Answers</b> button on the quiz form.
</p>
<aside>
<input name="quizclock" id="quizclock" value="0" />
<input id="start" type="button" value="Start Quiz" onclick="startClock()" />
<input id="stop" type="button" value="Submit Answers" onclick="stopClock()"/>
</aside>
</section>
</form>
</body>
The code that is provided is partial and I believe that is the only part of the code that is needed for the question. Thanks.
Reset Function as requested:
function resetQuiz() {
document.quiz.quizclock.value = 0;
for (i=0; i<document.quiz.elements.length; i++) document.quiz.elements[i].disabled=false;
document.quiz.stop.disabled = true;
}
You have two errors.
1. document.getElementByID('sth') should be document.getElementById('sth').
Notice the lowercase d at the end of Id.
2. You should put a . before value like this:
document.getElementById('quizclock').value = seconds;
This is all assuming that you have implemented startQuiz(), resetQuiz() and showQuiz() and they are working correctly.
Hope Helps;
Try to run the code snippet!
var Quiz = (function($) {
var updateView = function(timeElapsed) {
$('#result').html(timeElapsed);
};
function Quiz() {
updateView(this.timing);
}
Quiz.prototype.timing = 0;
Quiz.prototype.start = function() {
var self = this;
if(self._isCounting) {
return;
}
return this._interval = (function() {
self._isCounting = true;
var interval = window.setInterval(function() {
self.timing += 1;
updateView(self.timing);
}, 1000);
return interval;
})();
};
Quiz.prototype.stop = function() {
window.clearInterval(this._interval);
this._isCounting = false;
return this;
};
Quiz.factory = function() {
return new Quiz();
};
return Quiz;
})(window.jQuery);
window.jQuery(document).ready(function($) {
var historyQuiz = Quiz.factory();
historyQuiz.start();
var modalIsOpen = false;
$('#stop').click(historyQuiz.stop.bind(historyQuiz));
$('#resume').click(historyQuiz.start.bind(historyQuiz));
$('#submitQuizData').click(function(event) {
historyQuiz.stop();
return $.Deferred().resolve(historyQuiz.timing)
.then(function(val) {
return $('#quizResult').html(val + 's')
})
.then(function(element) { return element.fadeIn(); })
.then(function(element) { modalIsOpen = true; })
});
$('#quizResult').click(function() {
if(modalIsOpen) { modalIsOpen = false; return $('#quizResult').fadeOut(); }
});
});
.quiz-result {
display: none;
text-align: center;
width: 300px;
height: 300px;
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
<button id="stop">STOP QUIZ</button>
<button id="resume">RESUME QUIZ</button>
<button id="submitQuizData">SUBMIT QUIZ DATA</button>
<div id="quizResult" class="quiz-result"></div>

Viewport - jQuery selectors for finding elements in viewport

In my project every div has a video so I'm trying to check if a div is in viewport, so if it is that video to start playing and if it's not to pause or to stop. I'm jusing jekyll.
For example my html code for only one div looks like this :
<div class="container">
<div class="row">
<input type="button" id="play" value="Play"></input>
<input type="button" id="pause" value="Pause"></input>
<br/><br/>
<div class="col-lg-5 col-lg-offset-1 col-sm-push-6 col-sm-6">
<hr class="section-heading-spacer">
<div class="clearfix"></div>
<h2 class="section-heading">Vjetersia</h2>
<div class="lead"><p class="justify"> Vjetersia</p></div>
</div>
<div class="col-lg-5 col-sm-pull-6 col-sm-6">
<div class="gifv-player" id="">
<video preload="none" loop="loop">
<source type="video/webm" src="all_files/1.webm" />
</video>
<img src="example.png" alt="Animated Gif" />
</div>
</div>
<div class="col-lg-3 col-sm-pull-2 col-sm-2"></div>
</div>
</div>
I tried to do it on button click and it works:
$( document ).ready(function() {
player = new GifvPlayer();
$("#play").click(function() {
$('.gifv-player').find('video').show();
$('.gifv-player').find('video')[0].play();
});
$("#pause").click(function() {
$('.gifv-player').find('video')[0].pause();
});
});
but how can i modify it so it can work on stroll if a div is visible to start to play its video ? Any help?
easy quick and dirty example how you could implement it. play/pause like changing colors of the divs ... http://jsfiddle.net/7mkdj4ak/1/
var scrollPosition = $(window).scrollTop();
var windowViewHeight = $(window).height();
var videoWrapHeight = $('.container').outerHeight();
$(window).on('scroll', function(){
scrollPosition = $(window).scrollTop();
playVideos(scrollPosition);
});
$(window).on('resize', function(){
windowViewHeight = $(window).height();
});
var playVideos = function(scrollPosition) {
$('.container').each(function(i){
var thisContainerTopPosition = $(this).offset().top;
var thisContainerBottomPosition = thisContainerTopPosition + videoWrapHeight;
if(
thisContainerTopPosition >= scrollPosition &&
thisContainerBottomPosition <= (scrollPosition + windowViewHeight )
) {
/* div is in view PLaY */
$(this).css('background-color','orange');
} else {
/* div is out of view PausE */
$(this).css('background-color','#afafaf');
}
});
};
playVideos(scrollPosition);
.container {
width: 100%;
height: 100px;
background-color: #afafaf;
margin: 20px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h1>my Video 1</h1>
</div>
<div class="container">
<h1>my Video 2</h1>
</div>
<div class="container">
<h1>my Video 3</h1>
</div>
<div class="container">
<h1>my Video 4</h1>
</div>
You can refer this demo
.growme {
background-color: #990000;
height: 0;
width: 0;
position: absolute;
filter: alpha(opacity=0);
opacity: 0;
top:0;
left:0;
bottom:0;
right:0;
margin:auto;
}
DEMO HERE

Change Image on Scroll Position

I would like to change an image on a certain scroll position. For example:
Scroll 100px show img1.jpg
Scroll 200px show img2.jpg
Scroll 300px show img3.jpg
Here I found an example what I mean.
Any ideas?
You can use the onScroll event to listen for scrolling, check at what position the scrollbar is and make the image change or whatever your heart desires. You can read more about onScroll event here. A basic code will be something like this:
var onScrollHandler = function() {
var newImageUrl = yourImageElement.src;
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if (scrollTop > 100) {
newImageUrl = "img1.jpg"
}
if (scrollTop > 200) {
newImageUrl = "img2.jpg"
}
if (scrollTop > 300) {
newImageUrl = "img3.jpg"
}
yourImageElement.src = newImageUrl;
};
object.addEventListener ("scroll", onScrollHandler);
Of course yourImageElement should be replaced with the image element you want to change.
If you have jQuery availble you can use the .scroll() method instead of the event listener and the .scrollTop() to get the scrollbar position.
Also, you might want to look at some scroll/paralex libraries like skrollr.
$(window).on("scroll touchmove", function()
{
if ($(document).scrollTop() >= $("#one").position().top && $(document).scrollTop() < $("#two").position().top )
{
$('body').css('background-image', 'url(https://4.bp.blogspot.com/-Ivk46EkgQfk/WWjbo4TdJbI/AAAAAAAAFUo/gUD7JABklsIA1gWIr5LS1slyY4QuTMkEwCLcBGAs/s1600/gambar%2Bwallpaper%2Bmobil.jpg)')
};
if ($(document).scrollTop() >= $("#two").position().top && $(document).scrollTop() < $("#three").position().top)
{
$('body').css('background-image', 'url(https://i1.wp.com/cdn.catawiki.net/assets/marketing/uploads-files/45485-8bdcc8479f93d5a247ab844321b8b9d5e53c49a9-story_inline_image.jpg)')
};
if ($(document).scrollTop() >= $("#three").position().top && $(document).scrollTop() < $("#four").position().top )
{
$('body').css('background-image', 'url(https://s-media-cache-ak0.pinimg.com/originals/e1/7a/03/e17a0385726db90de1854177d4af2b4f.jpg)')
};
if ($(document).scrollTop() >= $("#four").position().top)
{
$('body').css('background-image', 'url(https://www.wallpaperup.com/uploads/wallpapers/2015/02/13/621414/6fc33c3ae65a58f9bb137f5cf011aebc.jpg)')
};
});
*{
margin:0;
padding:0;
}
.main{
width:100%;
height:100vh;
background-image:url('https://4.bp.blogspot.com/-Ivk46EkgQfk/WWjbo4TdJbI/AAAAAAAAFUo/gUD7JABklsIA1gWIr5LS1slyY4QuTMkEwCLcBGAs/s1600/gambar%2Bwallpaper%2Bmobil.jpg');
background-size:100% 100%;
background-attachment:fixed;
transition: 1000ms;
}
section{
width: 100%;
min-height: 1px;
}
.content{
width:50%;
min-height:1px;margin-top:10%;
margin-left:10%;
color:white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body class='main'>
<section id="one">
<div class='content'>
<h1 style='font-size:5vw;'>first heading</h1>
<p style='font-size:3vw;' >description</p>
</div>
</section>
<section id="two" style='margin-top:100vh'>
<div class='content'>
<h1 style='font-size:5vw;'>second heading</h1>
<p style='font-size:3vw;'>description</p>
</div>
</section>
<section id="three" style='margin-top:100vh' >
<div class='content'>
<h1 style='font-size:5vw;'>third heading</h1>
<p style='font-size:3vw;'>description</p>
</div>
</section>
<section id="four" style='margin-top:100vh' >
<div class='content' style='margin-bottom:10%;'>
<h1 style='font-size:5vw;'>fourth heading</h1>
<p style='font-size:3vw;'>description</p>
</div>
</section>
</body>
</html>
documentation
create a web folder first.
create a img sub folder // place all images into this folder
now create three files // in web folder
index.html
css.css
js.js
copy code given bellow and paste it.
save the program.
finally run the program
click on this link to see the video :https://www.youtube.com/watch?v=V97wCVY_SrQ
visit our website for full documentation :https://nozzons.blogspot.com/
index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href='css.css' rel='stylesheet' type='text/css'/>
<script src='js.js'></script>
</head>
<body class='main'>
<section id="one">
<div class='content'>
<h1 style='font-size:5vw;'>first heading</h1>
<p style='font-size:3vw;' >description</p>
</div>
</section>
<section id="two" style='margin-top:100vh'>
<div class='content'>
<h1 style='font-size:5vw;'>second heading</h1>
<p style='font-size:3vw;'>description</p>
</div>
</section>
<section id="three" style='margin-top:100vh' >
<div class='content'>
<h1 style='font-size:5vw;'>third heading</h1>
<p style='font-size:3vw;'>description</p>
</div>
</section>
<section id="four" style='margin-top:100vh' >
<div class='content' style='margin-bottom:10%;'>
<h1 style='font-size:5vw;'>fourth heading</h1>
<p style='font-size:3vw;'>description</p>
</div>
</section>
</body>
</html>
css.css
*{
margin:0;
padding:0;
}
.main{
width:100%;
height:100vh;
background-image:url('img/img_one.jpg');
background-size:100% 100%;
background-attachment:fixed;
transition: 1000ms;
}
section{
width: 100%;
min-height: 1px;
}
.content{
width:50%;
min-height:1px;margin-top:10%;
margin-left:10%;
color:white;
}
js.js
$(window).on("scroll touchmove", function()
{
if ($(document).scrollTop() >= $("#one").position().top && $(document).scrollTop() < $("#two").position().top )
{
$('body').css('background-image', 'url(img/img_one.jpg)')
};
if ($(document).scrollTop() >= $("#two").position().top && $(document).scrollTop() < $("#three").position().top)
{
$('body').css('background-image', 'url(img/img_two.jpg)')
};
if ($(document).scrollTop() >= $("#three").position().top && $(document).scrollTop() < $("#four").position().top )
{
$('body').css('background-image', 'url(img/img_three.jpg)')
};
if ($(document).scrollTop() >= $("#four").position().top)
{
$('body').css('background-image', 'url(img/img_four.jpg)')
};
});
So i am just answering this old thread because I was trying to implement the same thing on my website but i found it a bit difficult to implement it so I made a function of my own , its a bit easier to implement and understand but a bit buggy, For instance: if the user use the scroll bar instead of scroll wheel of the mouse the image will not change , hope it helps you :
<html>
<head>
<script>
function f() {
t1.src = "https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg"
t1.height = "319"
t1.width = "330"
}
function f2() {
t1.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Chess_piece_-_Black_queen.JPG/130px-Chess_piece_-_Black_queen.JPG"
t1.height = "319"
t1.width = "330"
}
function f3() {
t1.src = "https://asmoodle.asmadrid.org/blog/s16240/wp-content/uploads/sites/56/2014/12/protourney_knight_black_400.jpg"
t1.height = "244"
t1.width = "330"
}
function f4() {
t1.src = "https://thumbs.dreamstime.com/x/chess-knight-white-background-29811348.jpg"
t1.height = "244"
t1.width = "350"
}
function f5() {
t1.src = "http://cdn.craftsy.com/upload/3703789/pattern/115774/full_7439_115774_ChessKnightMachineEmbroideryDesign_1.jpg"
t1.height = "319"
t1.width = "350"
}
</script>
</head>
<body>
<div align="center" style="position: fixed; z-index: 20; left:38.5%; top:200">
<img src="no.png" height="319" width="330" name="t1">
</div>
</div>
<div class="container" onmouseover="f3()" style="padding:0; margin:0; width:100%;">
<img src="https://pixabay.com/static/uploads/photo/2016/01/11/22/05/background-1134468_960_720.jpg" width="100%">
</div>
<br>
<br>
<div class="container" onmouseover="f4()" style="padding:0; margin:0; width:100%;">
<img src="https://image.freepik.com/free-photo/lens-flare-abstract-backgound_21276999.jpg" width="100%">
</div>
<br>
<br>
<div class="container" onmouseover="f5()" style="padding:0; margin:0; width:100%;">
<img src="https://image.freepik.com/free-photo/lens-flare-abstract-backgound_21276999.jpg" width="100%">
</div>
<br>
<br>
<div class="container" onmouseover="f()" style="padding:0; margin:0; width:100%;"></div>
</body></html>
Cheers!!
Ha[ppy] Coding.

Sliding/Hiding Divs Issue

So I'm trying to make an accordion of sorts for my projects section of my website and I've run into a very strange issue (or maybe I'm just really tired). The first click to expand a selection works fine, but when the header is clicked again to return to the original state the contents of the previously expanded header become hidden. Furthermore, upon clicking the same header again to expand any time after the first the containing border disappears.
To see my problem in action just go to my website:
http://cole.quinnchrzan.com/cc2
and see for yourself by clicking on the projects section.
If you just want to take a look at the code here it is:
$(document).ready(function() {
var sign = 1;
$('#projects > div:not(.header)').on('click', function() {
if (sign == 1) {
$(this).css('border-bottom', 'none');
$(this).children().slideDown(400);
$(this).siblings().slideUp(400);
}
else {
$(this).css('border-bottom', '1px solid black');
$(this).children().slideUp(400);
$(this).siblings().slideDown(400);
$(this).css({
'height': '29px',
'z-index': '2'
});
}
sign = sign*-1;
});
});
and the HTML:
<section id="projects">
<div class="header">Websites</div>
<div>Saia LTL, Inc.
<div></div>
</div>
<div>Insurance House</div>
<div>Scandinavian Collectors Club</div>
<div>Casey Sills Photography</div>
<div class="header">Personal Projects</div>
<div>cTV</div>
<div>PoE DPS calculator</div>
<div>tSlide</div>
</section>
I added some extra css 'height': '29px' 'z-index': '2' to try and make the affected heading show again but it just creates an empty div. Without this css the div has no height.
try this.
live demo here
HTML
<section id="projects">PROJECTS
<div class="header">Websites</div>
<div>Saia LTL, Inc.</div>
<div>Insurance House</div>
<div>Scandinavian Collectors Club</div>
<div>Casey Sills Photography</div>
<div class="header">Personal Projects</div>
<div>cTV</div>
<div>PoE DPS calculator</div>
<div>tSlide</div>
</section>
JavaScript
var sign = 1;
$('#projects > div:not(.header)').on('click', function() {
if (sign == 1) {
$(this).css('border-bottom', 'none');
$(this).children().slideDown(400);
$(this).siblings().slideUp(400);
}
else {
$(this).css('border-bottom', '1px solid black');
$(this).siblings().slideDown(400);
$(!$(this).children(":first")).slideUp(400);
}
sign = sign*-1;
});
------------------------------------------------------------------------------------------------------------------------------------
ALTERNATE SOLUTION
live demo here
HTML
<section id="projects">PROJECTS
<div class="header">Websites</div>
<div>Saia LTL, Inc.</div>
<div>Insurance House</div>
<div>Scandinavian Collectors Club</div>
<div>Casey Sills Photography</div>
<div class="header">Personal Projects</div>
<div>cTV</div>
<div>PoE DPS calculator</div>
<div>tSlide</div>
</section>
JavaScript
var sign = 1;
$('#projects > div:not(.header) > .ShowThis').on('click', function() {
if (sign == 1) {
$(this).css('border-bottom', 'none');
$(this).children().slideDown(400);
$(this).parent().siblings().slideUp(400);
}
else {
$(this).parent().css('border-bottom', '1px solid black');
$(this).parent().siblings().slideDown(400);
$(this).children().slideUp(400);
}
sign = sign*-1;
});
It was a silly mistake. I simply forgot to select only div children when hiding/showing so the a children were remaining hidden or something. In other words I changed this:
$(this).children()
to this:
$(this).children('div')
Thanks to pfried for the indication!
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.js"></script>
<script>
$(document).ready(function() {
$('div.header div.slide').css('display','none');
$('div.header').toggle(
function(){$('div.header').hide('fast'); $(this).show('slow'); $('div.slide').css('display','block');},
function(){$('div.slide').css('display','none'); $('div.header').show('fast');});
});
$(document).ready(function(){
var text = $('div.cont');
$('div.slide').toggle(
function(){$('div.slide').hide('fast'); $(this).show('slow'); $('div.cont').css('display','block');},
function(){ $('div.cont').css('display','none'); $('div.slide').show('fast');});
})
</script>
<style>
.off{display: none;}
.on{ display: block;}
div.cont{ display: none;}
.slide{ display:none;}
</style>
</head>
<body>
<div id="projects">
<div class="header">Websites
<div class='slide'>Saia LTL, Inc.
<div class='cont'>a;dasndiasfhnip</div>
</div>
<div class='slide'>Insurance House<div class='cont'>dasndiasfhnip</div></div>
<div class='slide'>Scandinavian Collectors Club<div class='cont'>dasndiasfhnip</div></div>
<div class='slide'>Casey Sills Photography<div class='cont'>dasndiasfhnip</div></div></div>
<div class="header">Personal Projects
<div class='slide'>cTV<div class='cont'>dasndiasfhnip</div></div>
<div class='slide'>PoE DPS calculator<div class='cont'>dasndiasfhnip</div></div>
<div class='slide'>tSlide<div class='cont'>dasndiasfhnip</div></div></div>
</div>
</body>
i would prefer this one just try it
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>$(document).ready(function() {
var sign = 1;
$('#projects > div.header').on('click', function() {
if (sign == 1) {
$(this).css('border-bottom', 'none');
$(this).children().slideDown(400);
$(this).siblings().slideUp(400);
}
else {
$(this).children().slideUp(400);
$(this).siblings().slideDown(400);
$(this).css({
'height': '29px',
'z-index': '2'
});
}
sign = sign*-1;
});
$('div.slide').click(function(){
$('div.cont').slideToggle('slow');
});
});
</script>
<style>
div.cont{ display: none;}
</style>
</head>
<body>
<div id="projects">
<div class="header">Websites</div>
<div class='slide'>Saia LTL, Inc.
<div class='cont'></div>
</div>
<div class='slide'>Insurance House<div class='cont'></div></div>
<div class='slide'>Scandinavian Collectors Club<div class='cont'></div></div>
<div class='slide'>Casey Sills Photography<div class='cont'></div></div>
<div class="header">Personal Projects</div>
<div class='slide'>cTV<div class='cont'></div></div>
<div class='slide'>PoE DPS calculator<div class='cont'></div></div>
<div class='slide'>tSlide<div class='cont'></div></div>
</div>
</body>
i just tried adding a class to siblings to denote them specifically ---- is it u are looking I'm happy or anything else in particular please comment me ----- thankyou

Navigate to new content without page reload while updating the address field

I'm using Javascript to show documents. First, I hide the content that is loaded. Then, if a user press a button, the text related to that button will become visible while hiding other texts.
Currently, my technique does not change the URL that shows in the address bar.
I would like to update the address bar when a user clicks on one of the content display buttons. For example:
address.com/value_of_button
And if a user enters:
adress.com/a_value
I want to change display of div associated with the value. How is this done?
You can always use a hash url, and set the url like this:
function setHash(var hash) {
window.location.hash = hash;
}
If you want to retrieve the hash in the link to update the page, you can use something like
function getHash() {
return window.location.hash;
}
And to update the page you can just simply use if statements like this:
if(getHash() == "#main") {
document.getElementById('content').innerHtml = "<p>Main content</p>";
}
I had already demonstrated this at some point in the last year with jQuery. It's possible to not use jQuery, of course, but I'll provide you with the demo I created. I'll port an example to regular Javascript as well.
<html>
<head>
<style type="text/css">
.content {
display: none;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#menu a').each(function(){
id = $(this).attr('href');
id = id.substring(id.lastIndexOf('/'));
id = id.substring(0,id.indexOf('.'));
$(this).attr('rel',id);
});
$('#home').show();
$('#menu a').click(function(e){
e.preventDefault();
$('.content').hide();
$('#'+$(this).attr('rel')).show();
location.hash = '#!/'+$(this).attr('rel');
return false;
});
});
</script>
</head>
<body>
<div id="menu">
Home -
One -
Two -
Three
</div>
<div id="home" class="content">
Home content.
</div>
<div id="one" class="content">
One content.
</div>
<div id="two" class="content">
Two content.
</div>
<div id="three" class="content">
Three content.
</div>
</body>
</html>
EDIT
DOM method as promised:
<html>
<head>
<style type="text/css">
.content {
display: none;
}
</style>
<script type="text/javascript">
window.onload = function(){
var links = document.getElementById('menu').getElementsByTagName('a'),
divs = document.getElementsByTagName('div'),
sections = [],
id = '';
for (var i = 0, size = divs.length; i < size; i++) {
if (divs[i].className.indexOf('content') != -1) {
sections.push(divs[i]);
}
}
for (var i = 0, size = links.length; i < size; i++) {
id = links[i].href;
id = id.substring(id.lastIndexOf('/') + 1);
id = id.substring(0,id.indexOf('.'));
links[i].rel = id;
links[i].onclick = function(e){
e.preventDefault();
for (var p = 0, sections_size = sections.length; p < sections_size; p++) {
sections[p].style.display = 'none';
}
document.getElementById(this.rel).style.display = 'block';
location.hash = '#!/' + this.rel;
return false;
}
}
document.getElementById('home').style.display = 'block';
};
</script>
</head>
<body>
<div id="menu">
Home -
One -
Two -
Three
</div>
<div id="home" class="content">
Home content.
</div>
<div id="one" class="content">
One content.
</div>
<div id="two" class="content">
Two content.
</div>
<div id="three" class="content">
Three content.
</div>
</body>
</html>

Categories