Cycle through a list of html files with button - javascript

I have a list of products say:
laptops/prod1.html
laptops/prod2.html
laptops/prod3.html
monitors/prod1.html
monitors/prod2.html
monitors/prod3.html
I would like a button on my page that 'cycles' through the available items.
No idea how to do this. Is this possible with javascript?

function nextProduct(incr) {
var href = window.location.href
, offset = (typeof(incr)==='undefined' ? 1 : incr);
window.location = href.replace(/(\d+)\.html/, function(m, g1) {
return (Number(g1) + offset) + '.html'
});
}
Then you can do something like:
var button;
button = document.getElementByID('next-button');
button.addEventListener('click', function() { nextProduct(1); });
button = document.getElementByID('prev-button');
button.addEventListener('click', function() { nextProduct(-1); });

Setup a main page, this should not be a static html page but in your server side language of choice.
Include jquery to a main page using a script tag (you can get jquery from http://jquery.com/).
Your html could look like this:
<div id='content'></div>
<div>
<a href='javascript:void(0)' id='prev' class='btn'>Previous</a>
<a href='javascript:void(0)' id='next' class='btn'>Next</a>
</div>
In your js file you would have something like this:
var currPage = 0;
var pageList = ["laptops/prod1.html","laptops/prod2.html", "laptops/prod3.html"];
var totalPages = pageList.length;
$(".btn").on("click",function(){
//if we are at the last page set currpage = 0 else increment currPage.
currPage = currPage < (totalPages - 1) ? ++currPage : 0;
var page = pageList[currPage];
$('#content').load(currPage);
});
Some points to consider:
You will want to decide if the first page gets loaded on the main page load or on click
You will need to set a js variable to keep track of the currently loaded page
You will need to add some method of storing all the possible pages (think an array). This can get printed out to a script tag on the page on page load.
You need to decide what happens when you hit the end of the line. You can either cycle around or grey out the appropriate link.
jquery on
jquery load

Related

Anchorlinks in wordpress

I created a menu in wordpress that both contains anchorlinks to different sections on the startpage, and links to other pages:
But when I navigate to another page (ex "Jobs"), and from there try to navigate in manu to a section on startpage - anchorlinks doesn't work because it needs the full URL to guide user back to startpage and then jump down to the section i clicked. But when I change anchorlinks to full url:
..it will allways reload, even if i'm on startpage because I have the full url. How do i create a menu that will only have section URL (ex "#meetups") on the startpage, and full URL (ex "/hip#meetups") when I'm on another page.
Can I build a javascript or PHP function for this?
I really got stuck here and will be incredibly thankful for any input
I made a jQuery function that will alter menu-link-attr/url depending on browser.location:
var x = location.pathname;
if(x === '/hip/jobs/'){
var findLink = $('.menu-item-type-custom').find('a');
for (var i = 0; i < findLink.size(); i++) {
var attri = findLink.eq(i).attr('href');
findLink.eq(i).attr('href', "http://localhost:3000/hip/" + attri);
}
} else {
console.log('error! ' + x);
}

Create previous/next html page navigation

I have a series of pages named "page-1" "page-2" "page-3" ..."page-99". Is there a way to make a navigation so that whenever I click the "next" button it goes to the next page, and if I click "previous" it will go to the previous page depending on what the current page number is. I was wondering if there is a javascript solution to this since I have never used PHP.
next <!--it will go to page-3-->
previous <!--it will go to page-1-->
This should get you started (starting with your original code).
$('a[class^=page]').click(function(e){
e.preventDefault();
var num = this.className.split('-')[1]; //2
var nav = $(this).attr('data-nav');
if (nav == 'next'){
num = parseInt(num)+1;
//window.location.href = "page-"+num+'.html';
}else{
num--;
//window.location.href = "page-"+num+'.html';
}
alert('Navigating to: [ page-' +num+ '.html ]');
});
a{padding:10px;border:1px solid #ccc;border-radius:5px;text-decoration:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
next <!--it will go to page-3-->
previous <!--it will go to page-1-->
Of course, this would be easier:
$('a[class^=page]').click(function(e){
e.preventDefault();
var num = this.className.split('-')[1]; //2
//window.location.href = "page-"+num+'.html'; //The "real" code
alert('Navigating to: [ page-' +num+ '.html ]'); //For demo purposes only
});
a{padding:10px;border:1px solid #ccc;border-radius:5px;text-decoration:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" class="page-1" >next</a> <!--it will go to page-3-->
<a href="#" class="page-3" >previous</a> <!--it will go to page-1-->
And this would be easiest (using the file name):
//className *starts with* nav-
$('[class^=nav-]').click(function(e){
e.preventDefault();
var fileName = location.pathname.split("/").slice(-1);
var fileName = 'http://page-2.html'; //FOR DEMO ONLY
//alert(fileName); //should respond page2.html
var num = fileName.split('-')[1]; //2
var nav = this.className.split('-')[1]; //next
if (nav == 'next'){
num = parseInt(num)+1;
//window.location.href = "page-"+num+'.html';
}else{
num = parseInt(num)-1;
//window.location.href = "page-"+num+'.html';
}
alert('Navigating to: [ page-' +num+ '.html ]'); //For demo purposes only
});
a{padding:10px;border:1px solid #ccc;border-radius:5px;text-decoration:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" class="nav-next" >next</a> <!--it will go to page-3-->
<a href="#" class="nav-prev" >previous</a> <!--it will go to page-1-->
You can do this with PHP or JS. But in either case you first need to be able to programmatically determine the page number of the currently displayed page.
You mention PHP, is this WordPress or some other similar CMS?
Okay so you mentioned that this is a basic website, but we still need to be able to pull that currentPageID. We could do this a few ways, the coolest would probably be to take it from the url, so let's do that.
To get the number from the url structure you mention in comments (hostname.com/page-1.html):
// Let's first grab the url and pull just the last segment, in case there are numbers anywhere else in the url.
var url = window.location.href;
var array = url.split('/');
var lastSegmentOfUrl = array[array.length-1];
// Next, let's regex that last segment for the first number or group of numbers
var reg = /\d+/;
var currentPageID = lastSegmentOfUrl.match(r); // That's it!
// Then some basic math to get the next and previous page numbers
var previousPageID = currentPageID - 1;
var nextPageID = currentPageID + 1;
// And finally we change the href values on the next and previous <a> elements
document.getElementById('previous').href('/page-' + previousPageID + '.html');
document.getElementById('next').href('/page-' + nextPageID + '.html');
This will keep working forever assuming your url structure stays the same insofar as the last segment only has the current page number and no other numbers, and also that the next and previous anchor tags ID's don't change.
Here is a method using location.pathname and String.prototype.replace, no extra templating required!
Update Includes check that page exists before fetching.
// Check that a resource exists at url; if so, execute callback
function checkResource(url, callback){
var check = new XMLHttpRequest();
check.addEventListener("load", function(e){
if (check.status===200) callback();
});
check.open("HEAD",url);
check.send();
}
// Get next or previous path
function makePath(sign){
// location.pathname gets/sets the browser's current page
return location.pathname.replace(
// Regular expression to extract page number
/(\/page\-)(\d+)/,
function(match, base, num) {
// Function to increment/decrement the page number
return base + (parseInt(num)+sign);
}
);
}
function navigate(path){ location.pathname = path; }
var nextPath = makePath(1), prevPath = makePath(-1);
checkResource(nextPath, function(){
// If resource exists at nextPath, add the click listener
document.getElementById('next')
.addEventListener('click', navigate.bind(null, nextPath));
});
checkResource(prevPath, function(){
// If resource exists at prevPath, add the click listener
document.getElementById('prev')
.addEventListener('click', navigate.bind(null, prevPath));
});
Note that this will increment the "page-n" portion of the path, even if you are in a sub-path. It will also work for non-html extensions.
E.g.,:
mysite.com/page-100/resource => mysite.com/page-101/resource
or
mysite.com/page-100.php => mysite.com/page-101.php

Javascript taking too long to load

The javascript of the div "intro" is loading at last. It's taking too long to load as the web page loads the bg image first and then loads the java script. Is there a way i can display "loading please wait" message in that "intro" div until it completely loads. I just want that the intro should load first.
Javascript code:
var tl = new Array(
"=======================",
" Welcome user, ",
" ###########################################"
);
var speed = 50;
var index = 0;
text_pos = 0;
var str_length = tl[0].length;
var contents, row;
function type_text() {
contents = '';
row = Math.max(0, index - 20);
while (row < index)
contents += tl[row++] + '\r\n';
document.forms[0].elements[0].value = contents + tl[index].substring(0, text_pos) + "_";
if (text_pos++ == str_length) {
text_pos = 0;
index++;
if (index != tl.length) {
str_length = tl[index].length;
setTimeout("type_text()", 500);
}
}
else setTimeout("type_text()", speed);
}
This is the script and its basically typing letter by letter in a text area in the div "intro". The problem is that it loads at last when the whole page has loaded. It starts printing the text after like 15 seconds or so.
There are "domready" events you can listen to on the document but seems that's not cross-browser.
Eg: Mozilla
document.addEventListener("DOMContentLoaded", methodName, false)
A better option is to use jQuery's .ready() event. They handle all cross-browser implementations.
Eg:
$(document).ready(function(){
//execute code here
});
//Shorthand
$(function(){
//...
});
See this related question for more on domready.
Load a page with the empty intro div, run the script with "loading please wait" then trigger an ajax request to load the rest of the page and update the page on onComplete event from the ajax request
Using jQuery
$(document).ready(function() {
// update div here
});
http://api.jquery.com/ready/
Or you could do that with
window.onload= (function() {
// update div here
};
You can use jquery for this by wrapping the content in a div tag and then another div that holds a loading image, something to this effect:
$(document).ready(function () {
$('#loading').show();
$('#divShowMeLater').load(function () {
$('#loading').hide();
$('#divShowMeLater').show();
});
})
Assume divShowMeLater is the div that contains all the content being loaded. The markup would look similiar to this:
<div id="divShowMeLater" style="margin-left:auto;margin-right:auto;text-align:center;" >
<div id="loading">Page loading...
<img src="images/ajax-loader.gif" alt="loading page..." />
</div>
</div>

JavaScript previous and next buttons to cycle through an array of .js files

I am having difficulty writing some JavaScript that will cycle through an array of .js files.
I have some JavaScript widgets saved in .js files.
I want to be able to click a "Next" or "Previous" button to cycle through an array of those .js files and have the widgets called and displayed on my HTML page. They can be displayed in an iFrame if that would be a better solution.
I will continue researching until a kind soul helps out. Thanks a bunch in advance!
I have tried:
<script>
function onWindowLoad(){
document.getElementById('js_type').innerHTML = ****.settings.type;
var widget_arr = [1column.js,2column.js,1row.js,modal.js]; //etc..etc..
var currentWidget = 0;
theBtn.onRelease = function(){
currentWidget++;
if(currentWidget == widget_arr.length){
currentWidget=0;
}
var selectedWidget = widget_arr[currentWidget];
//now you have a variable pointing to the next widget..
//what you do with it is up to you.. add the code you need..
}
and this
<SCRIPT LANGUAGE="JavaScript">
<!--
// Use the following variable to specify
// the number of widgets
var NumberOfWidgets = 4
var widget = new Array(NumberOfWidgets)
// Use the following variables to specify the widget names:
widget[0] = "1column.js"
widget[1] = "2column.js"
widget[2] = "1row.js"
widget[3] = "modal.js"
var widgetNumber = 0
function NextWidget()
{
widgetNumber++
if (widgetNumber == NumberOfWidgets)
widgetNumber = 0
document.widgets["VCRWidget"].src = widget[widgetNumber]
}
function PreviousWidget()
{
widgetNumber--
if (widgetNumber < 0)
widgetNumber = NumberOfWidgets - 1
document.widgets["VCRWidget"].src = widget[widgetNumber]
<IMG SRC="modal.js" NAME="VCRWidget">
}
//-->
</SCRIPT>
Code for the previous and next buttons:
<A HREF="javascript:PreviousWidget()">
<IMG SRC="prev.png" BORDER=0></A>
<A HREF="javascript:NextWidget()">
<IMG SRC="next.png" BORDER=0></A>
One idea can be to use the fact thst even a static page can have parameters in the url. You can for example:
create the html page that will be opened in the <iframe> with any js include you need (e.g. jquery)
add to this page a js function that given a widget js filename will create a <script> tag loading the widget creation code.
extract the name of the js file to use to call the function in (2) from document.location.href by looking at the part of the string after ?
in your main page create dinamically the iframe using for example contdiv.innerHTML = "<iframe src=\"widgetpage.html?" + widgetname + ".js\"></iframe>";
With this approach the widgets will be shown in a separate html page without interferring with your main page.

Manipulate DOM element to extract some nodes and remove others

I need to manipulate HTML code. Specifically, the user should be able to copy/paste the code to create an AddThis button in a textarea, and I want to manipulate the pasted code.
A typical AddThis button looks like this :
<!-- AddThis Button BEGIN -->
<div class="addthis_toolbox addthis_default_style ">
<a class="addthis_button_facebook_like" fb:like:layout="button_count"></a>
<a class="addthis_button_tweet"></a>
<a class="addthis_counter addthis_pill_style"></a>
</div>
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=ra-123456798"></script>
<!-- AddThis Button END -->
It consists of start and end comments, a div and/or some links, followed by 2 scripts: a config setting, and a call to their library.
The problem is, we need to call this many times on the page ; so, if I just put this every time I want to place an AddThis button, I fear that at least some browsers will have weird behavior, if it works at all.
So, I want to extract the config setting and the lib call, so I can call them just once, and extract the buttons config, so I can place it as many times as I want on the page.
I have already done that :
var codeAT = $(this).val();
if (codeAT.indexOf("AddThis Button BEGIN") >= 0) {
codeAT = codeAT.replace("<", "<");
codeAT = codeAT.replace(">", ">");
codeAT = $(codeAT);
// extract the call to the config var and the lib
var scriptConfig = "";
var scriptSRC = "";
codeAT.each(function() {
if ($(this).attr("nodeName") == "SCRIPT") {
if ($(this).attr("src") && $(this).attr("src") != "") {
scriptSRC = $(this).attr("src");
} else {
scriptConfig = $(this).text();
}
}
});
// extract the addthis identifier
scriptSRC = scriptSRC.split("=")[1];
}
Now, I can use the vars scriptConfig (with var addthis_config = {"data_track_clickback":true};) and scriptSRC (with ra-123456789), and they have the correct values.
What I want now, is the original code (between the two comments), without the comments, and without the script tags.
To remove the tags, I tried to use codeAT.remove($(this)), but it crashes (something about c.replace not being a function).
To get the code back, I tried codeAT.html(), but it gets only the tags.
Instead of .each() I'd do:
//remove <script> tags and get required info
var scriptSRC = $('script[src]', codeAT).remove().attr('src');
var scriptConfig = $('script:not([src])', codeAT).remove().text();
//get the code (as string)
var code = $('<div>').append(codeAT).remove().html();

Categories