Refresh div with button click using random javascript string element - javascript

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();
});

Related

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

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.

javascript runtime error 0x800a1391

I'm learning a bit HMTL5 to prepare to the 70-480 exam. I'm trying to do some javascript code. It looks something like this:
function inchestometers(inches) {
if (inches < 0)
return -1;
else {
var meters = inches / 39.37;
return meters;
}
}
var inches = 12;
var meters = inchestometers(inches);
document.write("the value in meters is " + meters);
var hello = document.getElementById("hello");
hello.firstChild.nodeValue = "Hello World";
and I have such html code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Htnl 5 test</title>
<script src="script/test.js"></script>
</head>
<body>
<p id="hello">Hello</p>
</body>
</html>
In my VS 2012 i have used the Asp.net Empty Web application project and added the Js file and also the html file. The problem is that The function runs properly without any exeptions. This function is taken from here: http://msdn.microsoft.com/en-us/library/cte3c772(v=vs.94).aspx
But whem I'm trying to run the code where I'm getting the document element it' crashint with the error like in the subject. What I've investigated is that the hello gets the null value. I've also tried the code thaken from here:
http://msdn.microsoft.com/en-us/library/yfc4b32c(v=vs.94).aspx - the example with the div. I have the same effect.
What is wrong? I know that there were simmilar subjects but I can't seem to find one matching to mine. Thank you kindly for your help.
Regards
Rafal
you are getting a problem because your javascript code is running before the element
<p id="hello">
is defined.
the simplest solution is to include your script at the end of the body section instead of in the head section but this would cause the document.write call to occur after the rest of the content.
another solution would be to place the code inside two functions like this
function do_conversion() {
var inches = 12;
var meters = inchestometers(inches);
document.write("the value in meters is " + meters);
}
function say_hello() {
var hello = document.getElementById("hello");
hello.firstChild.nodeValue = "Hello World";
}
then change the body section like this
<body onload='say_hello()'>
<script>
do_conversion();
</script>
<p id="hello">Hello</p>
</body>

deleting random words from html page

I created a javascript program that prints element from my array one by one when you click on the title "click here" , my problem here is that tried to implement a function that deletes a random word from the html page when you click on the words printed previously but it printing other words instead, how can i create a function that removes words printed previously ?
<!DOCTYPE html>
<html>
<head>
<title>function JavaScript</title>
<script >
var k = 0;
var ph = ["red ","blue","black","green","yellow"];
function text(){
if(k < ph.length ){
document.getElementById("test").innerText+=" "+ ph[k];
k++;
}
}
function deleteWord(){
var number = Math.floor(Math.random() * 5);
document.getElementById("test").innerText+=" "+ ph[number];
}
</script>
</head>
<body>
<h1 onclick="text();">Click here</h1>
<span id="test" onclick="deleteWord();"></span>
</body>
</html>
function deleteWord(){
var number = Math.floor(Math.random() * 5);
document.getElementById("test").innerText+=" "+ ph[number];
}
Your problem is that the += operator appends " "+ ph[number] after the current value of the string.
To replace instead, use the = operator to assign a new value. since you want to delete, just use an empty string.
document.getElementById("test").innerText = "";
As a side note it is unusual to store multiple spaces in your string. If you are trying to move the contents around, you should probably consider setting the padding-left CSS property instead.
edit: if you don't want to lose the entire contents of the element, you can replace the last part of the string:
document.getElementById("test").innerText.replace(/ .*$/,"");

JS Variable Passing Via URL

I am designing a webpage that loads images of a document into the webpage and then will relocate to a specific image (page) based on a variable passed from another page. The code is below. Right now, it does not look like the variable 'page' is being updated. The page will alert
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<!-- Javascripts -->
<script type="text/javascript">
var pageCount = 40; /*Total number of pages */
var p; /*Variable passed to go to a specific page*/
function pageLoad(){ /*Loads in the pages as images */
for( i = 1; i<= pageCount; i++){
if(i < 10){
i = "0"+i;
}
document.body.innerHTML += "<div class='page'><a id='page" + i +"'><img src='pages/PI_Page_"+ i +".png' /></a></div>";
if( i == pageCount){
gotoPage(p);
}
}
}
function gotoPage(pageNum){ /* Moves webpage to target page of the PI */
window.location = ("#page" + pageNum);
alert(p);
}
function Test(){
window.open("./PI.html?p=15","new_pop");
}
</script>
</head>
<body onload="pageLoad()">
<div class="ExtBtn" onClick="Test()">
<img alt="Exit" src="design/exit_btn-02.png" />
</div>
</body>
</html>
The function TEST() was set up to allow me to have a link to re-open the page with p set to 15. The page opens, however, the function gotoPage() still alerts that p is undefined. Any ideas why that is?
Variables passed in the URL do not automatically become variables in JavaScript. You need to parse document.location and extract the value yourself.
p is never set a value anywhere so of course it will be undefined. You need to pull the value from the query string manually, JavaScript does not magically get the query string value for you.
Use the function here: How can I get query string values in JavaScript? to get the value.
Also why are you checking for the last index, set the go to call after the for loop.
Here is your code with the correct alert(p) working:
http://js.do/rsiqueira/read-param?p=15
I added a "function get_url_param" to parse url and read the value of "?p=15".

Categories

Resources