How to make a html page pick a random title on load? - javascript

I'm new to web development and can't seem to find this specific task anywhere on this site, only things related to dynamic changes while using a page. Basically, I want the contents of the tag in my part of my html document to always be different when loading/refreshing the page; I want to store some kind of array of strings in JS, and have the page, upon loading the html, pick one of these strings to insert into the tag.
This will result in every time I refresh the page, the title on the tab is different, and will not change unless I refresh again.
Can anyone point me to how I might do this? Completely stuck, and out of ideas after my window.onload didn't work.
EDIT: I have tried this code based on what I found on this site, but the title didn't change; and I'm not sure why.
var titles = ['rainy skies == best', 'now with more bugs!', 'c > java'];
window.onload = function() {
document.title = titles[(Math.random() * 10) % 2];
$('meta[name="description"]').attr("content", 'My website!');
};
(This is then linked into the html page as per usual)

You can add a little piece of Javascript. It will be executed each time the page loads and can change the page title dynamically.
<script>
var titles = ['asdf', 'qwer', 'uiop']
var title = titles[Math.floor(Math.random() * titles.length)] // pick random item
document.title = title
</script>
The usage of a backend language like PHP can solve the issue too, but this is much simpler.

Server-side example. Define a list of titles, pick a random one, and output it in the title attribute.
Get random item from array
PHP
<?php
$titles = ['title1', 'title2', 'title3'];
?>
<html lang="">
<head>
<title><?php echo $titles[array_rand($titles)]; ?></title>
</head>
...
</html>

You should use document.title to change the title in the tab of the website.
const strings = ["bar", "foo", "banana", "apple", "orange", "red", "green", "blue", "brown", "gray"];
window.onload = () => {
let random = Math.floor(Math.random() * strings.length);
// example with a div
document.getElementById("my-span").innerHTML = strings[random];
// example with page title
// document.title = strings[random];
};
<span id="my-span"></span>

HTML:
<head>
<title id="title"></title>
</head>
Javascript:
window.onload = function() {
var titles = ['rainy skies == best', 'now with more bugs!', 'c > java'];
var random = Math.floor(Math.random() * titles.length);
var titleElement = document.getElementById('title')
titleElement.innerHTML = titles[random];
}
EDIT: innerHTML instead of html

Related

Function output of JavaScript function not showing in html

The Javascript code is working but I don't know how I can make it work in HTML. I want to link it to an external Javascript file.
function find_longest_string(input_array) {
var large = input_array[0].length; //storing the length of each word in the variable large
input_array.map(var_new => large = Math.max(large, var_new.length)); //used map to check the largest word
answer = input_array.filter(var_new => var_new.length == large); //storing the words which are larger
return answer[0]; //displaying the first largest word
}
console.log(find_longest_string(['mystery', 'brother', 'aviator','crocodile','pearl','orchard','crackpott']))
HTML code:
<!DOCTYPE html>
<html>
<body>
<script src="findLongestWord.js"></script>
</body>
</html>
I believe you want to print or display the output of that function on the web page.
If that's the case. There are various ways to accomplish this.
Before I go any further, I'd want to point out that you are, in fact, printing something, which is what you intended for your function.
But you can't see it since it's printed in the console.
You may view this by using the F12 key after loading your website.
The console will then appear, and the needed output will be printed.
And here's one method for displaying your output in an HTML page.
You just have to replace your console.log() with the document.write().
function find_longest_string(input_array) {
var large = input_array[0].length; //storing the length of each word in the variable large
input_array.map(var_new => large = Math.max(large, var_new.length)); //used map to check the largest word
answer = input_array.filter(var_new => var_new.length == large); //storing the words which are larger
return answer[0]; //displaying the first largest word
}
document.write(find_longest_string(['mystery', 'brother', 'aviator','crocodile','pearl','orchard','crackpott']))
<!DOCTYPE html>
<html>
<body>
<script src="findLongestWord.js"></script>
</body>
</html>
Here is another method to achieve this.
You can add an html element and change the content of that particular element by using document.getElementById("id name of the element").innerHTML.
Here is the code snippet.
function find_longest_string(input_array) {
var large = input_array[0].length; //storing the length of each word in the variable large
input_array.map(var_new => large = Math.max(large, var_new.length)); //used map to check the largest word
answer = input_array.filter(var_new => var_new.length == large); //storing the words which are larger
return answer[0]; //displaying the first largest word
}
const largest_word = find_longest_string(['mystery', 'brother', 'aviator','crocodile','pearl','orchard','crackpott']);
document.getElementById("demo").innerHTML =largest_word
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script src="findLongestWord.js"></script>
</body>
</html>

PHP, JS - Documenting and saving DATE/TIME to re-appear after browser closed

I currently have a sitation where I can click on an image and it will return a new image, and in the previous grid-item, it will return the day and time I clicked it.
What I want is to have this BUT where I also can see the updated image and clicked time after closing and re-opening the browser. - What is the easiest / quickest way to achieve this?
I feel like adding to my database would be a way forward, but if that is what I would need to do, how would I go about storing and out-putting the time based on the time I click?
(This is not intended to be a live site, or for others to see or use, so local quick-fixes are viable).
foreach ($flavours as $key => $flavour) {
echo "<div class='grid-container'>";
echo "<div class='item7'><p id='p3'>Sylus: </p></div>";
echo "<div class='item8'><img src='htts://i.i.com/k.jpg' onclick='cS(this)' /></div>";
echo "</div>";
}
function cS(element) {
if (element.src == "htts://i.i.com/k.jpg")
{
element.src = "http://i.i.com/v.jpg";
var d = moment().format('dddd HH:mm');
element.parentElement.previousElementSibling.firstChild.innerHTML = "Sylus: " + d;
}
else
{
element.src = "htts://i.i.com/k.jpg";
element.parentElement.previousElementSibling.firstChild.innerHTML = "Sylus: ";
}
}
Try this example using localStorage. This will find the <p> tag elements within the body, and then uses each element to get the id for reference.
I tried using a fiddle here, but the site has a security complaint with the localStorage.
Copy/paste this code to a file to give it a try. Note that you will likely need to update the moment.js reference in this code to match your file path.
<!doctype html>
<html>
<head>
<title>localStorage example</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="moment.js"></script>
</head>
<body>
<div class='grid-container'>
<div class='item7'><p id='p0'>Sylus: </p></div>
<div class='item8'><img src='htts://i.i.com/k.jpg' onclick='cS(this)' /></div>
</div>
<div class='grid-container'>
<div class='item7'><p id='p1'>Sylus: </p></div>
<div class='item8'><img src='htts://i.i.com/k.jpg' onclick='cS(this)' /></div>
</div>
<script>
function cS(element) {
var pTag = element.parentElement.previousElementSibling.firstChild;
if (element.src == "htts://i.i.com/k.jpg")
{
element.src = "http://i.i.com/v.jpg";
var d = moment().format('dddd HH:mm');
var pText = 'Sylus: ' + d;
pTag.innertHTML = pText;
// Set (save) a reference to browser localStorage
localStorage.setItem(pTag.id, pText);
}
else
{
element.src = "htts://i.i.com/k.jpg";
pTag.innerHTML = "Sylus: ";
// Remove the stored reference. (delete this if not needed)
localStorage.removeItem(pTag.id);
}
}
$(document).ready(function() {
pElements = $('body').find('p').each(function(index, element) {
// Get the localStorage items. The retrieved <p> elements,
// we use their id value to reference the key in storage.
storageItem = localStorage.getItem(element.id);
if (storageItem) {
$('#' + element.id).text(storageItem);
}
});
});
</script>
</body>
</html>
After clicking an image (will need to replace with something real), open the browser's web inspector interface, click the Storage tab, and then expand the Local Storage in the list (see image below), and choose the file being tested.
There will be key/value pairs displayed. The keys are references to the <p> tag id's, and the value will have a label-date strings such as Sylus: Wednesday 22:28.
Once you see an entry, or two, being set to the storage, close and then reopen the browser tab. The <p> elements that had dates should be reloaded with their values from the storage.
The browser's Local Storage area should be similar to the image below:
save it to local storage, or a cookie with the exp. date too far in the future

Refresh div with button click using random javascript string element

There are several similar questions, so I hope this is a unique problem. None of the proposed solutions on those similar questions have solved my issue. Humble apologies from this beginner if I messed up somehow.
I have an empty div on my page with I am loading using javascript with strings from an array. Currently, I have a script running on a button which reloads the entire page. I would like for that button to just reload the div with items from my javascript array.
Here is my code:
<html>
<head>
<link rel="stylesheet" href="obliqueStyle.css">
<style></style>
</head>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<body>
<div id="wrapper">
<div id="strategyBox"></div>
<div id="button">
<a class="againbutton" onclick="buttonReload()">Again</a>
<script>
var buttonReload = function() {
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
}
</script>
</div>
</div>
<script src="os.js"></script>
</body>
Here is a snippet of my array and the JS (coming from the os.js file referenced in index.html) I am using to load the div initially/on refresh:
var obliqueStrategy = ["Abandon normal instruments",
"Accept advice",
"Accretion",
"A line has two sides"];
var randomStrategy = obliqueStrategy[Math.floor(Math.random() * obliqueStrategy.length)];
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
I've tried calling the same javascript as a function in script in the html like this:
<div id="button">
<a class="againbutton" onclick="buttonReload()">Again</a>
<script>
var buttonReload = function() {
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
}
</script>
</div>
I've tried using the jQuery AJAX load function like this:
<script>
$(function() {
$("#againbutton").on("click", function() {
$("#strategyBox").load("index.html")
return false;
})
})
</script>
I've played around with variations of the above and tried a couple other things that I'm forgetting exactly how and what I did, so I can't include them. I've really hit a wall on this even though it seems profoundly simple.
Thanks in advance for any help.
Here's one method: http://jsfiddle.net/kxqcws07/
HTML
<div id="wrapper">
<div id="strategyBox"><p id="strategyText"></p></div>
<div>
<input type="button" class="againbutton" value="Again">
</div>
</div>
Javascript
//wrapping your logic in a namespace helps reduce the chances of naming collisions of functions and variables between different imported js files
var localNameSpace = function() {
//private array containing our strings to randomly select
var obliqueStrategy = [
"Abandon normal instruments"
, "Accept advice"
, "Accretion"
, "A line has two sides"
];
var api = {
//bindButtonAction binds the generateRandomStrategy function to the click event of the againbutton
bindButtonAction: function() {
$('#wrapper .againbutton').click(api.generateRandomStrategy);
}
, generateRandomStrategy: function() {
//get the position of one of the string randomly
//Math.random() returns a float value < 1 so multiplying it by 100 gets us a range of (0.* - 99.*)
//then we Math.floor() that to get rid of the float value and keep just the integer part
//finally we modulus it with the length of the string array
//if you are unfamiliar with modulus, what it does is gives you the remainder of a division. for instance 10 / 3 gives you 3 with a remainder of 1, so 10 % 3 would be just 1.
//what this does for us is keeps the random offset of our within the bounds of the array length (0 to length -1)
var randomOffset = Math.floor(Math.random() * 100) % obliqueStrategy.length;
//finally once we have the offset, we set the html to the string at the position in the array
$('#wrapper #strategyBox #strategyText').html( obliqueStrategy[randomOffset] );
}
};
return api;
}();
$(document).ready(function() {
//here we call the bind action so the button will work, but we also explicitly call the generateRandomStrategy function so the page will preload with a random string at the start
localNameSpace.bindButtonAction();
localNameSpace.generateRandomStrategy();
});

Having a cycled (interval) pictures on pre-loaded page through a directory

I am currently working for a library that would like to have a webpage designed digital signage. Most of it has been designed with widgets and through a program called Xcite Pro. I was unable to find any widgets that will allow me to do a slideshow from a directory that will cycle through. I do know the foundations to JavaScript and php.
I do not know how to take a directory and have JavaScript run through an entire directory into a array with picture values. I would like to use the setInterval() command but I seem to only know how to search through a directory by php. I did find a explanation on this site that tells me how to use php to search through and then pull all pictures to be shown. If i can get that to all go into an array that could be used with JavaScript on the site that would actually work fine. The link for that explanation is LINK.
Currently I am just using a folder called pics in my main file. So my directory is "pics" nothing to special. I have seen some things being talked about html5 using a new file search function but that sounds more like for finding particular files rather then taking the entire components of a folder into an array.
Edited 12/23/2013 Per PHPGlue Request and help.
So far the code that I have played with are:
Test html (Main Page)
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Basic XHTML Document</title>
</head>
<body>
<p>President Obama is from Hawaii</p>
<p><img id="scroller" alt="" src="pics/test.jpg" width="600" height="400"/></p>
<script type='text/javascript' src='common.js'></script>
<script type='text/javascript' src='pics\imagefun.php'></script>
</body>
</html>
Common js File in main directory with main page
// common.js
//<![CDATA[
var doc = document, bod = doc.body, IE = parseFloat(navigator.appVersion.split('MSIE')[1]);
function gteIE(version, className){
if(IE >= version){
bod.className = className;
}
}
function E(e){
return doc.getElementById(e);
}
//]]>
Finally I have 2 pictures in a picture folder along with a imagefun php file.
// imagefun.php
<?php
$imgs = implode(array_merge(glob('*.png'), glob('*.jpg')), "', '");
echo "//<![CDATA[
var imgs = ['$imgs'], ni, iA = [];
for(var i in imgs){
ni = new Image; ni.src = imgs[i]; iA[i] = ni;
}
var pre = onload, iN = 0, iL = imgs.length-1, imgElementId = E('scroller');
imgElementId.src = imgs[0];
onload = function(){
if(pre)pre();
imgElementId.src = iA[0];
setInterval(function(){
if(iN >= iL)iN = 0;
imgElementId.src = iA[++iN];
}, 2000);
}
//]]>";
?>
PHPGlue-- Thank you for all the time that you have put into this. Really not trying to be a pain at all and I really do appreciate all of your patience. I have made sure to swap names based on my file structures. Based on what I see for the basic ideas of the code I would think it should work. As I said though when I load to test it, it will only show the picture I defaulted on the load and then never change. One thing that I have noticed is that if you take the code of the image fun php code and run just that, all it returns is an output of //=IL)iN = 0; imgElement.src = iA[++iN]; }, 2000; } //]]> If I am right then that string of output should be similar to the whole thing rather then just a fragment of a line like it is. I do believe if I am understanding the goal of this code we are having it spit out some code into the src location of the picture location?
Ultimately if possible I would like to have a cloud based file location that I could use to have an individual who works here store pictures in that file and then have the website pull all files in that location to be loaded to the page one at a time at an interval of about 15000ms. I would appreciated any comments or recommendations.
I ended up resolving this myself. Thank you for all the help.
This was a multi parter either way.
I created a php cycler code
Note** This code will actually run through all that was needed just in php. Sadly though as I wanted this to show up on a web page that would cycle on a timer I needed to use some javascript coding. This caused me to change parts of what was used. If you want to do the same thing you drop all code after you have created the pics array or you can even keep up to the point of the forwards and backwards array to be passed into javascript.
<?php
// create a variable to hold the directory location
$Dir = "..\Directory\pics";
// Variable to directory
$dirOpen = opendir($Dir);
// Need to start with a main array
$pics = array();
// Need two arrays for going forward and back
$forwards = array();
$backwards = array();
// Need variables for the program
$c = 0;
$d = 0;
$e = 0;
$i = 0;
$f = 0;
// Need to run through all files in folder and store into an array
while ($curFile = readdir($dirOpen))
{
if(strpos($curFile,'.jpg') !== false)
{
$pics[$i] = $curFile;
++$i;
}
}
closedir($dirOpen);
// declare variables to count previous opening of file
$a = count($pics); // number of pics in the folder
$b = count($pics) - 1; // need to account for starting at 0
// run through pics array fowards
while($f < $a)
{
$forwards[$f] = $pics[$f];
++$f;
}
// run through the pics array backwards
while($b > -1)
{
$backwards[$c] = $pics[$b];
--$b;
++$c;
}
// variables for the functions us
// use function for forward pics
/*function forward($array, $a)
{
$d = 0;
if($d == $a)
{
$d = 0;
return "pics/".$array[$d];
++$d;
}
else
{
return "pics/".$array[$d];
++$d;
}
}
function backward($backwards, $b)
{
if ($e == $b) // going to have a conflict with B becuase right now it should be at -1 or 0. need to compare to the value of -1 and have it reset to the max when reached.
{
}
}
*/
/*// Test the output of each array
foreach($pics as $imgs)
echo $imgs . "<br />";
foreach($forwards as $fors)
echo $fors . "<br />";
foreach($backwards as $backs)
echo $backs . "<br />";
*/
// $forwards and $backwards are the arrays to use for pics cycling
?>
To pass onto the java script I had to use the following code on another php page created to work with all html design of the main page.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
</head>
<body>
<form name="myForm">
<p> </p>
<p> </p>
<p class="auto-style1"><img alt="" src="" id="pics" height="400" width="300"/></p>
<?php include 'imgCycler.php'; ?>
<script type='text/javascript'>
/* <![CDATA [ */
var forwards = <?php echo json_encode($forwards); ?>;
var backwards= <?php echo json_encode($backwards); ?>;
var max = <?php echo $a ?>;
var count = 0;
function changePic()
{
document.myForm.pics.src='pics/' +forwards[count];
//document.myForm.pics2.src='pics/'+backwards[count];
++count;
if (count == max)
{
count = 0;
}
}
var start = setInterval('changePic()',5000);
</script>
</body>
</html>
Again PHPGlue thank you for all the help you offered. Hope this is useful for anyone else that wishes to do something similar. Please let me know if there are any questions on the code.
Let's start by making a common.js file:
// common.js
//<![CDATA[
var doc = document, bod = doc.body, IE = parseFloat(navigator.appVersion.split('MSIE')[1]);
function gteIE(version, className){
if(IE >= version){
bod.className = className;
}
}
function E(e){
return doc.getElementById(e);
}
//]]>
Now put the script below in the same folder you keep your images in:
// imagefun.php
<?php
$imgs = implode(array_merge(glob('*.png'), glob('*.jpg')), "', '");
echo "//<![CDATA[
var imgs = ['$imgs'];
for(var i in imgs){
new Image().src = imgs[i];
}
var pre = onload, iN = 0, iL = imgs.length-1, imgElement = E('imgElementId');
imgElement.src = imgs[0];
onload = function(){
if(pre)pre();
imgElement.src = imgs[0];
setInterval(function(){
if(iN > iL)iN = 0;
imgElement.src = imgs[iN++];
}, 2000);
}
//]]>";
?>
Change the imgElementId to yours inside E('imgElementId'). E('imgElementId') must refer to an <img id='imgElementId' /> tag.
Now on your HTML page, refer to this JavaScript page as PHP, at the bottom of your body:
<script type='text/javascript' src='common.js'></script>
<script type='text/javascript' src='path/imagefun.php'></script>
</body>
</html>
Also, change src='path/ to your image folder path, and add or subtract the correct , glob('*.jpg')s and the like, to suit your needs.
Notes:
E(id) gets your Element by id. bod.className changes to the <body class='njs'> to <body class='js'>, assuming you have the class attribute njs in your HTML body tag, for CSS without JavaScript (progressive enhancement). gteIE(version, className) is for Internet Explorer versions greater than or equal to a number passed as version, changing that version or greater's body class attribute to the className argument, because IE10+ won't accept HTML IE comments for CSS changes. imgfun.php caches the images into your Browser memory based on globs found in the folder the script resides in. Then, once these images are loaded into your Browser cache, they are cycled through using setInterval.

External Javascript File Fetch?

I am currently using this code:
var wordRandomizer = {
run: function (targetElem) {
var markup = this.createMarkup();
targetElem.appendChild(markup);
},
createMarkup: function () {
var that = this;
var frag = document.createDocumentFragment();
this.elem = document.createElement('span');
var button = document.createElement('button');
button.innerText = 'Change Item';
button.addEventListener('click', function () {
that.changeItem();
});
frag.appendChild(this.elem);
frag.appendChild(button);
return frag;
},
changeItem: function () {
var rand = this.getRandInt(1, this.items.length) - 1;
console.log(rand);
this.elem.innerText = this.items[rand];
},
getRandInt: function (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
},
items: ['itemA', 'itemB', 'itemC', 'itemD']
};
wordRandomizer.run(document.body);
I code is a button which when pressed grabs one of the items in the list. However, I don't want the items to show on the same page as the generator as people simply look at the source code. How can I make it so once the button is pressed it grabs the random item from another location where people cannot view them all using the source code.
If it helps, you can see the code in action here - http://jsbin.com/ESOdELU/1/edit
I will give you a solution using PHP since it is a free scripting language and is the most likely to be supported by a host or default web server...
For starters, here is the code to include jquery and the basic AJAX script
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/JavaScript">
$(document).ready(function(){
$("#generate").click(function(){
$("#madlibs p").load("script.php");
});
});
</script>
Here is the code for script.php
<?php
header("Cache-Control: no-cache");
// For testing you can use an inline array like the lines below
// Just remove the comment slashes "//" from the beginning of the line
// and comment out the external declarations
//$actors = array('Denzel Washington','Michael J. Fox','Jim Carey','Boris Kodjoe');
//$roles = array('Mental Patient','Homeless Musician','Drag Queen Detective','Tormented Mathematician');
// In production, you would put these in a text file or a database.
// For $actors, put an entry on each line of a text file and save it as 'leads.txt'
// Do the same with a separate file for $roles (roles.txt).
$actors = file("leads.txt");
$roles = file("roles.txt");
// This selects a random element of each array on the fly
echo $prefixes[rand(0,count($actors)-1)] . " stars as a "
. $suffixes[rand(0,count($roles)-1)] . " in the next blockbuster film.";
// Example output:
// Michael J. Fox stars as a Tormented Mathematician in the next blockbuster film.
?>
Put this in the body of your page and be sure to style everything up for display.
<body>
<div id="madlibs"><p> </p></div>
<button id="generate">Surprise Me!</button>
</body>
A couple of notes:
- You can include your basic layout HTML in the script.php file and then would only need the ID of the DIV in which you will be displaying the result $("#madlibs")
You can use any server side language to achieve the same result, just swap out the external file call to the appropriate name and extension (.asp, .cfm, etc.)
Here is a link to the original tutorial that helped me with a similar project:
http://www.sitepoint.com/ajax-jquery/
I hope this helps. Sorry, but I couldn't come up with a purely Java of JavaScript solution on lunch.

Categories

Resources