Pull in random html page - javascript

I have a comic website www.twistedshotgun.com and it has a random button with some javascript someone made for me. I now need something that is easier to update.
I need the random button to choose a random html page, but I dont want to manually add each webpage to each html page, because as I make more pages it means changing every single individual page that has a random button to add the new content.
So is there a way to have an external file that lists all the random pages in one file so I can just update that?
I do not know javascript but this is my current code, but this is on every page:
<script type="text/javascript">
//INDEX VERSION ONLY
//pages (use full url if in a different domain);
var page1 = "comics/101/longbear.html";
var page2 = "comics/102/do_bees_pump.html";
var page3 = "comics/103/how_I_feel_on_a_daily_basis.html";
var page4 = "comics/104/windows_8 _space oddity.html";
//array (add all the pages inside [])
var pages = [page1,page2,page3,page4];
function showRandomPage()
{
var num = Math.round(Math.random() * (pages.length-1));
window.location.href=pages[num];
console.log(num);
};

To keep the information about the random pages between sessions, store the list of the random pages in a database and access the database whenever you want to get to the random URL.
Another possibility is to store the list in Javascript, in an external file (depending on how long it is).

Since the pages are all in different directories, there is no need or benefit to them having different names, and as you'll see there's a lot of benefit in them being the same, so I recommend renaming your page files to the same name, which might as well be simply index.html.
If your pages have the same name, your random selection script becomes very simple:
<script type="text/javascript">
function showRandomPage() {
var num = 100 + Math.round(Math.random() * 4);
window.location.href = "comics/" + num + "/index.html";
console.log(num);
};
</script>
If you number your directories sequentially from 100 on up (not skipping any numbers), all you need to do to maintain your code is increase the 4 in the code to whatever is quantity of pages you have.

put your random generating page java script in a file with extension .js , say pagedatabase.js
now in your html page where you want to call the function
place this code above it.
<script src="pagedatabase.js"></script>
it should work. id did for me. i too had the same problem with big database of header scripts.
keep in mind that the script call and the function call should be in the same region. do not place one in the head and other in the body. your html editor will give an error.

Related

Load all images from folder and roll them in JS slider with Laravel framework

What is the best way to roll all images from folder in JS slider with Laravel framework ? This is current code with hard-coded image paths:
var i =0;
var images = [
'images/sliders/background_slider/2.jpg',
'images/sliders/background_slider/3.jpg',
'images/sliders/background_slider/1.jpg',
'images/sliders/background_slider/4.jpg',
'images/sliders/background_slider/5.jpg'];
var image = $('#slideit');
image.css('background-image', 'url(images/sliders/background_slider/1.jpg)');
setInterval(function(){
image.fadeOut(200, function () {
image.css('background-image', 'url(' + images [i++] +')');
image.fadeIn(1000);
});
if(i == images.length)
i = 0;
}, 5000);
});
This code works well, but my idea is to have an option to easy manage this pictures without touching the code. I have tried to create an PHP variable with all paths of images and then to use it in JS with json_encode function but this doesn't work. Also, when i load these paths in JS variable, i can easily see them in source view in every browser and i think, that's not a good idea from security point of view.
So, what's the best way to do that ?
Thanks in advance!
D.T.
You can't hide the variable if you want to use it in client side JS. It would be the same as hard coding the array, with the only difference that it will be rendered using server side script in order to make it dynamic.
So, if your php variable is $images, it should look something like this:
$images = [
'images/sliders/background_slider/2.jpg',
'images/sliders/background_slider/3.jpg',
'images/sliders/background_slider/1.jpg',
'images/sliders/background_slider/4.jpg',
'images/sliders/background_slider/5.jpg'];
And to pass it to your view, you can do:
$data['images'] = json_encode($images);
Then, in the view, instead of hard coding the values, you'll get them from your php variable. Convert the json string back:
var images = JSON.parse('<?=$images?>');
And, to set the first image as background:
image.css('background-image', 'url('+images[0]+')');
UPDATE:
I just noticed you are counting the elements of the image array, which you won't be able to do with the object generated after JSON.parse. Instead, you can create an array of keys for every object element and count that instead.
images_keys= $.map(images, function(v, i){
return i;
});
And wherever you need images.length, you can go with images_keys. For everything else, you can use the images object itself.

How do I make relative file pathing work with include()?

I'm working on a website, and the relevant portion of my file structure is:
site
classes
class1
js
Now, the js contains scripts that use other scripts within the same folder. The only way I can get the scripts to load properly on the php pages is to either copy the whole js folder into the relevant subfolder, or move the page to the site folder. Neither of these options is good.
I know that the issue is with the file pathing, so how do I get the includes in the js scripts to path relative to their location, and not the location of the php page?
An example of this:
I have a page in class1 called class1home.php.
It calls a js script called script.js.
script.js contains a function with include(script2.js), which is in the js folder.
Because of the pathing, the include is looking for site/classes/class1/script2.js.
I want it to go to site/js/script2.js.
Because there are multiple folders and scripts using script2.js, I can't just change the filepath within the include to be relative to that specific page.
Within script.js:
/**
* #function Include
* #description Includes an external scripts to the page
* #param {string} scriptUrl
*/
function include(scriptUrl) {
document.write('<script src="' + scriptUrl + '"></script>');
}
One place it is used (within script.js):
/**
* #module ToTop
* #description Enables ToTop Plugin
*/
(function ($) {
var o = $('html');
if (o.hasClass('desktop')) {
include('js/jquery.ui.totop.min.js');
$(document).ready(function () {
$().UItoTop({
easingType: 'easeOutQuart',
containerClass: 'ui-to-top fa fa-angle-up'
});
});
}
})($);
I normally solve this type of problem by having the page identify where it is with a call to Server. It looks like this:
$callingPageURL =$_SERVER['SCRIPT_FILENAME'];
Then, I parse that string to determine the file and the folder, by using the explode function. It looks like this:
$callingPageURLHolder = explode("/", $callingPageURL);
This loads up an array of values into callingPageURLHolder. From there, I use common data structure methods, like array pops, to get to the part of the URL that I think will be relevant to the program. It looks like this:
$callingPageFile = array_pop($callingPageURLHolder);
$callingPageFolder = array_pop($callingPageURLHolder);
Once you can parse out the array that comes back from Server, you could simply load up variables you need to concatenate into a URL that you will call in your include.
This same type of technique can be used to make small changes in a template page based on where it was included from, by adding in some flow control that tests these kinds of extracted values.
For example,
switch ($callingPageFile){
case "index.php":
// some response
break;
}
Using logic like that, I might build chains of cases in which I respond to anticipated URL parts. I use this type of code for when I might want to slightly customize a PHP page. Using these techniques, and some planning, you might be able to respond to the idea that you intend to transplant your code to a variety of places.

exchange variables between html files in javascript

I am trying to share variables between two html pages. I am only using javascript and HTML5 to develop a windows 8 app. Based on an image which a user clicks on one page, I want a div on a second page to be populated with that image. Any ideas?
When I click on the image, I am currently calling the following function:
function imageClick(url) {
//var id = parsed.ClientID;
//window.location= url + "?" + id
window.location = url;
}
Then in my html file, I have this line:
<img onclick="imageClick('pages/page2/page2.html')"
data-win-bind="src:image" style="width: 133px; height: 125.5px;">
I was thinking of getting that id in the next page's url (if I were to uncomment the commented lines above) but it's a bit hackky and I don't actually know how to go about executing the retrieval of that on the next page..
Is there a more efficient and easy way of doing this in javascript? Like an equivalent of sessions in php or something?
Javascript does not have session variables because it runs on the client side. You can use URL parameters and cookies in order to achieve the same results.
You can get the URL parameter by using this function:
http://ziemecki.net/content/javascript-parsing-url-parameters
Add the link to the image to the query part of the url when they click. Something like you had in the comment, assuming you don't have a query part already:
function imageClick(url) {
//var id = parsed.ClientID;
window.location= url + "?src=" + url.src;
//window.location = url;
}
The other page can use window.location.search to extract it, strip off the src=. The code would look something like this:
var src = window.location.search;
if (src.indexOf("src=") == 0) {
src = src.substring(4);
}
newPageImageElement.src = src;
Where newPageImageElement is the <img> where you want to display the picture on the second page.

Tipue Search (Jquery)

I'm trying to customize a Tipue search script.
Currently the script is searching the entire HTML file (including metadata) and triggering false positives on the search results. I'd like to eliminate the metadata from the critera or only allow the script to search a specific DIV (i.e. #pagewrap).
Here is a link to the current script:
http://www.worldonecommunications.com/ndrill/tipuesearch/tipuesearch.js
(Lines 37-77)
The pages are being indexed in a separate file, but I think the problem lies in the file listed above.
I think you need to change these lines:
var t_1 = html.toLowerCase().indexOf('<title>');
var t_2 = html.toLowerCase().indexOf('</title>', t_1 + 7);
...
var t_1 = html.toLowerCase().indexOf('<meta name="description"');
var t_2 = html.toLowerCase().indexOf('"', t_1 + 34);
I'am also searching a way how to modify this engine to out results from page body.
For others who are interested:
The developer finally updated the search script to target only a specific DIV. The updated code can be downloaded from their site:
http://www.tipue.com/search/

random images from a folder

I am trying to rewrite my code below to search a folder for all the images (they will be numbered but there maybe gaps, ie not 1.jpg,2.jpg,3.jpg but instead 1.jpg,15.jpg,60.jpg for this reason i would like to search the folder, put all the images into an array and then pick one randomly each time its looped.
Any help would be greatly appreciated.
Firstly i am currently specifying image total above the main script below:
imgWidth = 160,
imgHeight = 95,
imgTotal = 22,
total = 0,
tiles;
//create the HTML for the tiles and append that to the bg element
function makeTiles(count){
var html = '', imgNum;
while(count--){
imgNum = Math.floor(Math.random()*imgTotal + 1);
html += "<div class='tile' style='background:url(public/images/portfolio/all/"+imgNum+".jpg) 0 0 no-repeat;' ><img style='opacity:0; filter:alpha(opacity=0);' src='public/images/portfolio/all/"+imgNum+"-c.jpg' alt='' /></div>\r";
}
$bg.append(html);
}
You'll need to create a list of available images with something else than javascript, since it has no filesystem access, even though in the end, you are accessing the images via their url.
Workaround: enable some directory listing for the images, then access this page via javascript, parse the image files and construct an array out of them; but frankly, there are shorter and more robust ways to accomplish this ...
pseudocode ..
$ ls -1 *jpg > imagesfilelist.txt
$ cp imagefilelist.txt /some/publicly/accessible/folder
js/jquery ..
$.get("/some/publicly/accessible/folder/imagefilelist.txt", function(data){
alert("My image files: " + data);
});
...
javascript can not access local folders. point.
I repeat: there is no way you can "search folder" to get "array of images" in JS. You could do that part (server only!) in PHP or such server-side language and return results via AJAX.
To do what you want you need to know what the images are called. JavaScript cannot access folder directly as commented above. You would need to use a server side script to provide an array of the images for the JS to pick at random to do this.
Javascript will not be able to browse folders. What you need to do is to create an array of available images and then select a random one. You could do this using any server side technology (php, rails, java, .net ...).
The way you're trying to do it is a wrong one.But iwth a bit of tricks it could work though, but it's very wrong way to do this kind of things.
You can generate file list with php and feed it to your script. You can even create php script which will generate your script already populated with needed data but it's not the best to do this too.
So, the best ways are:
- create html with list of filenames/images(visible or invisible) by php, then manipulate it by javascript;
- create html and javascript wich will do AJAX query to php script which will return filename list(formated as JSON if you wish).
Why not upload your images to a free hosting site (like Flickr) grab the feed from your image group and select the random image from there?

Categories

Resources