Random text to be displayed in body of HTML - javascript

I want to insert a randomly selected piece of text into the page when it loads. The possible pieces of text are stored in an array within a function called randomtext.
<script type="text/javascript">
function randomtext() {
var randomtxt=[
'Beautiful People are not always Good but Good people are always Beautiful!',
'50% + 50% off check here',
'New Arrivals Click here<img src="http://mastimix.in/pictures/icon-new.gif"/>',
'We changed our terms and conditions > check '
];
return randomtxt[Math.floor((Math.random() * 3.99))];
}
</script>
Now I want to display any one of the line randomly whenever the page is loaded or refreshed inside the <body> tag, or any particular area I want to place the line.
Now tell me what to write there in <body> tag?

As you've worked to improve your question and you did have a working function for randomText. If you add a target to the HTML like <p id="spam"></p> and then add document.getElementById("spam").innerHTML = randomtext(); it will display the output from your randomtext in the spam paragraph.
http://jsfiddle.net/qVf8G/
This code is using the native JavaScript methods for finding the spam paragraph document.getElementById("spam") and then addressing the content of it as innerHTML and assigning the random text to it.

Related

How to change add and remove tags with JS in django template

I have a quiz Django app which consists of two parts. One is showing 10 sentences with their audio to remember, one per page, and the second is asking questions for the same set of sentences. First part was set up with js function which creates pagination in my html the following way:
my_template.html
<button id="prev">prev</button>
<button id="next">next</button>
<ul class="list-articles" id="dd">
</ul>
<script>
var my_objects = `{{ my_objects|safe}}:` #list of items from my view function
function paginate(action) {
console.log(action)
if (action ==='next') {
page_number++;
}
else{
page_number--;
}
const audio = document.createElement('audio');
audio.src =`/media/${my_objects[page_number].fields.audio}`;
$('#dd').empty();
$('#dd').append('<li><h1>'+ my_objects[page_number].fields['content'] +'</h1></li>');
$('#dd').append(audio);
$('#page_number').val(page_number);
}
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#next').onclick = function() {
paginate('next'); #same goes for 'prev' button.
}
})
</script>
Now when the user paginated through all the sentences I want to show the continue button and if the user clicks it, start the second part. The second part has absolutely same page except I need to hide content of my objects and leave only audio or vice versa and add textarea tag for the user's input. After that I need to loop over my objects again - now in the form of questions. I need to do that without page re-rendering so I don't need to store the list of objects or query the DB again.
I tried to make it with tag disabling and activating the second loop after the first ends but that looks quite messy and I suppose there is a smarter way of doing that. I'm not a JS developer so any help would be appreciated!
Thanks for all who viewed and not commented! I found the answer myself. Just need to add JS functions which will empty the main tag and refill with necessary field.
Details: By accessing elements of DOM in the following way you can empty any element on a web page. For example, if we have a div like:
<div class= id="maindiv">
<h2> Hello, world! </h2>
</div>
We can empty and refill it with a new header:
var container = document.getElementById("maindiv");
container.empty();
new_header = document.createElement('h2');
new_header.innerHTML = 'Hello, brave new world!'
container.append(new_header);
Same applies to the whole web-page. The only thing is, if it is too big, you probably going to be tired of manipulating the DOM each time. So, you may want to check out some frameworks like React to make it easier .

How to pass a div created with javascript to another page with php

I don't know how to display my divs in another page after created them. When the divs are created with their function, after clicking a button, they will be displayed in a div in the main page, right after that, there has to be a redirection to the second page, passing the divs created.
example how the main page works: Jsfiddle
I don't know how to send and display the divs just created, in a second page.
I think that the action should be set with php but I don't know...
IMPORTANT
You don't have to understand the Js code. You only have to know that the divs that I want to copy to the second page, at the beginning, don't exist. So the "copy-to-the-new-page" action has to be done after the creation of the divs.
Main Page:
<html lang="it">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css"/>
</head>
<body>
<div id="faketxt" contenteditable>Write Here</div>
<button id='btn'>OK</button> <br>
<div id='boxes'>
</div>
<script type="text/javascript">
$('#btn').click(function() {
var primo = document.getElementById('faketxt');
var wordLimit = 145;
var words = primo.textContent.replace(/(<([^>]+)>)/ig,"").split(/\s/);
if (words.length) {
var count = 0;
var div = createDiv();
words.forEach(function(word) {
if (++count > wordLimit) {
count = 1;
div = createDiv();
}
if (div.innerHTML) {
div.append(' ');
}
div.append(word);
});
}
});
function createDiv() {
div = document.createElement('div');
div.className = 'fakes';
document.getElementById('boxes').append(div);
return div;
}
</script>
</body>
</html>
You shouldn't have to send the entire div just the amount of data that's required for the next page to recreate it.
i.e. you could use a cookie and have the user remember:
document.cookie = "divinfo=The text field of the div's;\
path=/";
have a hidden input field that contained the relevant information.
<input name="divinfo" hidden value="The info required for the creation of the div"/>
If you use the cookie the javascript could recreate the data on the other side if you use the hidden input you should have the php recreate it.
well, you have at least 3 ways to do it, and it all comes down to how to pass enough information between 2 pages:
1) you may get HTML of those divs when they are just created, store it in session storage, and re-create divs from the stored html. That way you dont have to know much about the divs on the 2nd page, but there is a limit on how much you can store. Also, may pose some security/privacy risks if information is sensitive, so you may have to do some extra coding to mitigate it.
2) you may re-create those divs on the 2nd page based on the same set of information you used to create those on the first page. JS code could be shared between the two.
3) use server side to generate div's content. That way you can generate both 1st and 2nd page content.
Or is there something I miss about the problem?
Create a hidden text input in the submit form
Add the new div value to that hidden input
Submitting the form will send the value to the next page through php
Now pick that value in javascript using php like
var xyz = '';
Now you can use this value whatever you want
I don't know why the values with php tag is not showing here :(
I suggest a few changes. First all all, use a proper form - kind of like you had in the first revision of your question.
<form action="download.php">
<input id="faketxt" type="text" value="Write Here" />
<button id='btn'>OK</button>
</form>
<div id='boxes'></div>
Now, on the second page, you have all the information you need in your form field "faketxt" and just can create the divs there. Depending on which method you are using (POST/GET) you have access to the data like following:
<?php echo $_POST["faketxt"]; ?>
Secondly I suggest, you change you code slightly, to make it a bit more readable.
$('#btn').click(function() {
var primo = document.getElementById('faketxt');
var wordLimit = 5;
var words = primo.value.replace(/(<([^>]+)>)/ig,"").split(/\s/);
while (words.length > 0){
let div = createDiv();
div.append(words.splice(0,wordLimit).join(" "));
}
});
See your modified fiddle.

how to convert output from alert box to display on page - javascript/html

I'm trying to write a script that counts specific words from <td>'s on my page and displays the total within an HTML element. In this example I am counting how many times the word "Complete" appears within tables. So the half-way-there script I have now is as follows:
<p>
<script>
$(document).ready(function(){
var x = $("td");
alert($('td:contains("Complete")').length);
});
</script>
</p>
This works pretty well, when the page loads an alert box pops up and correctly counts the occurrences of the word "Complete." My hang up is how do I modify this to display on the page instead of with the alert box? I've tried using innerHTML shown here and analyzed a number of similar questions here on stack overflow trying to mimic the examples, but I always break the counting function when trying to adapt it over.
This is my first time writing js and here is my latest attempt which makes me feel like that dog who has no idea what he's doing:
<p class="completed">
<script>
$(document.getElementById("completed")).innerHTML(function(){
var x = $("td");
$('td:contains("Complete")').length;
});
</script>
</p>
Insights into how I can fix the second code block is very much appreciated. Thanks!
Simply print the output where you want instead of to an alert box. Consider the following:
<p>
<script>
$(document).ready(function(){
var x = $("td");
// Print out the result to the #resultsGoHere element
$('#resultsGoHere').html($('td:contains("Complete")').length);
});
</script>
</p>
<p id="resultsGoHere"></p>

How would I make a self-linking <div>?

After much Googling, I resort to the chance at ridicule and moderation on Stack Exchange.
What I am trying to do sounds simple enough. I want to make a <div> id/class that will link automatically create a link to itself via some kind of scripting.
Let me put down some pseudocode, before I make it sound more complicated than it is:
#Let div.link = xxx.html
#Let div.pic = xxx.png/jpg
for div in HTMLdocument:
if div.class == "autolink":
div = "<img src=\"mysite/" + div.pic + ">"
Now, obviously that's Python pseudocode, but I am familiar(ish) with PHP and Javascript. Basically, I want to make the div generate an HTML link without having to actually type out the tags and links for every given div on a web page. I want to be able to type, in my index.html:
<html>
<head></head>
<body>
<div class = "1"></div>
<div class = "2"></div>
</body>
</html>
and then to be presented with a page that has the two divs linked, imaged, and, preferably, formatted.
Like I said, the problem seems simple, but I can't seem to get it to work right, in any language. This seems like a thing that would be very useful for begiiner web designers.
PERSONAL NOTE:
I would preferably like to see a solution in PHP or Javascript, but if you are good with Django and want to show me how to get it done in that, I would be just as grateful!
=========================================
EXAMPLE:
Let's say you have a browser based RPG, and you want to show your player's inventory. The Inventory page would display the items in a players inventory, complete with a link and image, based on whatever was in that user's inventory page. It would look like this (this is VERY rough output, Statements tagged in #these# are not code, and should be interpereted as what they describe):
<h1>User's Inventory:</h1>
<p><div class = "item_1">#Link to page of 'item_1', image of 'item_1'#</div></p>
<p><div class = "item_2">#Link to page of 'item_2', image of 'item_2'#</div></p>
The above would display, roughly, a header that said "User's Inventory", and then display a linked image of item_1, followed by a newline and then a linked image of item_2, where said items would be in a separate file OR a list that lists all the items and their respective links and images.
You can use jquery, and when page dom is loaded, you cycle through each div that has the class autolink and do your manipulations (add your desired html into each div). You can use the id of each div to place data inside. You can use a prefix to that id values for different types of data. For example, im using "inventory_" as a prefix.
<h1>User's Inventory:</h1>
<p><div class = "autolink" id="inventory_item_1">#Link to page of 'item_1', image of 'item_1'#</div></p>
<p><div class = "autolink" id="inventory_item_1">#Link to page of 'item_2', image of 'item_2'#</div></p>
then jquery on document ready:
<script type="text/javascript">
$(document).ready(function ()
{
// define your website here
var mysite = "http://www.example.com/";
// this will cycle through each div with class autolink. using `this` to reffer to each.
$(".autolink").each(function () {
// we get for div with id="inventory_item_1" ...
var mylink = $(this).attr('id').replace("inventory_",""); // ... a value item_1
var myimagesrc = $(this).attr('id').replace("inventory_","image_"); // ... image_item_1
$(this).html('<img src="'+mysite+'images/'+myimagesrc+'.jpg">');
// the above will add html code of this format:
// <img src="http://www.example.com/images/image_item_1.jpg">
});
});
</script>
try it here:
http://jsfiddle.net/5APhT/2/
I'll give a sample in php. Here is an example if you already have a set of links to use
<?php
//Create a multidimensional array to store all you need to create links
$links['1'][]="http://www.yahoo.com";
$links['1'][]="yahoo.com";
$links['2'][]="http://www.facebook.com";
$links['2'][]="yahoo.com";
$links['3'][]="http://www.google.com";
$links['3'][]="yahoo.com";
foreach($links as $class => $innerArray){
$link=innerArray[0];
$linktext=innerArray[1];
echo "<div class='$class'><a href='$link'>$linktext</a></div>";
}
?>
This creates the divs for you so you don't have to add them in advance.
You can add images in the same manner

Filter out HTML Tag onpaste for div and oncopy too

I have an editable DIV in my site to send a forum message. People can edit their messages (Bold, Italic, underline, add links and more)
But I want when some one paste or drop (- drop is not necessary, but paste it is) their text I want it to go in the DIV without HTML tags - clean, just text. (like if some one is going to word and make the text 200 points size, then copy & paste it in my DIV, they will have a very different message... and I don't want it to happen).
How can I scan the text coming from the clipboard to remove any HTML tags and then paste it in the DIV?
<html>
<head>
<script type="text/javascript" language="javascript">
function PasteFilter()
{
//windows.clipboardData filter on paste to go here
}
function CopyFilter()
{
//windows.clipboardData filter on copy to go here
}
</script>
</head>
<body>
<Div class="body" onpaste="PasteFilter()" oncopy="CopyFilter">
<!-- div content goes here.-->
</Div>
</body>
</html>
I would like to also apply the same filter with COPY too.
Thanks
I believe there are 2 ways to do this:
1) The easy way - insert the following code in PasteFilter():
var foo = window.clipboardData.getData('Text');
window.clipboardData.setData('Text', foo);
the first line gets the Text value of clipboardData (already stripped of HTML tags)
and the second line sets the clipboardData to the plain text...
(Tested on IE8)
2) The other way - if for some reason that isn't suitable for you..
In PasteFilter(), you trigger another function with a small delay timeout.
In that function, you get the innerHTML contents of the DIV and run a regular expression to remove all tags.
Example:
function PasteFilter()
{
setTimeout('foo()', 200);
}
function foo()
{
var contents = document.getElementById("test").innerHTML;
var new_contents = contents.replace(/(<([^>]+)>)/g, ""); // taken from http://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/
document.getElementById("test").innerHTML = new_contents;
}
The problem with this method is that you lose the caret position...
Hope this helps...

Categories