How to change font inside a javascript code - javascript

I am a newbie in programming. I have here my javascript code. Its working fine but I want a different style.
this code is a random quote generator.
<html>
<head>
<title>
Daily Quotes
</title>
</head>
<h1>Inspirational Quotes</h1>
<body>
<script language="JavaScript">
var quoteGroups=70;
var quoteNum;
var theQuote=new Array();
theQuote[0]='Whenever you see a successful business, someone once made a courageous decision. - Peter Drucker';
theQuote[1]='If you\'re not part of the solution, you\'re part of the problem. - African Proverb';
theQuote[2]='When you confront a problem you begin to solve it. - Rudy Giuliani';
theQuote[3]='I dream of painting and then I paint my dream. - Vincent Van Gogh';
theQuote[4]='Be silent or let thy words be worth more than silence. - Pythagoras';
theQuote[5]='The past cannot be changed. The future is yet in your power. - Mary Pickford';
theQuote[6]='Anything\'s possible if you\'ve got enough nerve. - J.K. Rowling';
var quoteNum = Math.round(Math.random() * quoteGroups);
document.write(theQuote[quoteNum]);
</script>
<div>
<button style="background-color:lightgreen;width:230;height:70;border: none; font: bold 25px GreatVibes;" onclick="history.go(0)">Inspire Me More!</button>
</div>
<div>
<button style="background-color:blue;width:200;height:70" onclick=>Share</button>
</div>
</body>
<img src="images/bg.jpg" id="bg" alt="">
</html>
For example, the above code will generate random quotes. Now how do i change the font family as a result of clicking the button from this code?
Thanks in advance.

Looking at this:
<button style="background-color:blue;width:200;height:70" onclick=>Share</button>
You have no function set to onclick. Do something like:
<button style="background-color:blue;width:200;height:70" onclick="changeFont(this, 'font name');">Share</button>
changeFont:
function changeFont(element, name) {
element.style.fontFamily = name;
}

Some things to improve:
Don't use document.write, but instead reserve an element in your HTML that you will populate with the quote, assigning to textContent;
Don't use round in your random generating expression, but floor, otherwise you risk to produce a value that is out of range
Don't use a separate variable for the number of quotes you have (which currently does not match the actual number), but use theQuote.length
Don't define long style values in your HTML, but use CSS classes instead
Don't reload the page at every click, but change the quote within the current page without navigating.
To dynamically set the font, you could reserve a few CSS classes to choose from, even randomly.
Here is how it could work:
function displayQuote() {
var theQuote= [
"Whenever you see a successful business, someone once made a courageous decision. - Peter Drucker",
"If you're not part of the solution, you're part of the problem. - African Proverb",
"When you confront a problem you begin to solve it. - Rudy Giuliani",
"I dream of painting and then I paint my dream. - Vincent Van Gogh",
"Be silent or let thy words be worth more than silence. - Pythagoras",
"The past cannot be changed. The future is yet in your power. - Mary Pickford",
"Anything's possible if you've got enough nerve. - J.K. Rowling"
];
var quoteNum = Math.floor(Math.random() * theQuote.length);
var clsName = "special" + Math.floor(Math.random() * 3); // choose random font style
quote.textContent = theQuote[quoteNum];
quote.className = clsName;
}
next.onclick = displayQuote; // execute on click
displayQuote(); // execute on page load
.shareButton {
background-color:blue;
width:200;
height:70
}
.inspireButton {
background-color:lightgreen;
width:230;
height:70;
border: none;
font: bold 25px GreatVibes;
}
.special0 {
font-family: Georgia;
font-size: 24px;
color: #444;
}
.special1 {
font-family: Calibri;
font-size: 32px;
color: #844;
}
.special2 {
font-family: Tahoma;
font-size: 28px;
color: #484;
}
<div id="quote">
</div>
<div>
<button id="next" class="inspireButton">Inspire Me More!</button>
</div>

As you are new, it's best not to pick up bad habits which, unfortunately is easy to do because so much of the code out there is just copied and pasted by folks who don't know any better, so:
Try not to write inline styles or inline event handlers like this:
<button style="background-color:lightgreen;width:230;height:70;border: none; font: bold 25px GreatVibes;" onclick="history.go(0)">Inspire Me More!</button>
As you can see, it makes the code difficult to read as there are 3 languages in that one element!
Instead, separate your languages into their own sections, or even files.
With regard to CSS styles, it would be better to define CSS classes ahead of time and then just switch to the class you need, rather than write all that inline CSS.
You also have some errors in your code.
So, here's an updated version of your code that also changes the font. Make sure to review the comments for details.
<html>
<head>
<title>Daily Quotes</title>
<style>
/* We'll separate the CSS into this section and prepare pre-made classes for styles.
See how much cleaner this is, not only here but in the HTML as well? */
button {
background-color:lightgreen;
width:230;height:70;
border: none;
font: bold 25px GreatVibes;
}
.share {
background-color:blue;
width:200px; /* Don't forget to add the unit */
height:70px; /* Don't forget to add the unit */
}
#output {
/* Now, just the output area has its own style! */
font-family: fantasy;
}
</style>
</head>
<body>
<!-- All your content must be between the opening and closing body tags. -->
<h1>Inspirational Quotes</h1>
<div>
<button>Inspire Me More!</button>
</div>
<div>
<button class="share">Share</button>
<img src="images/bg.jpg" id="bg" alt="">
</div>
<!-- Don't use document.write() to inject content into a page. Instead, prepare an
element ahead of time that you will update later. -->
<div id="output"></div>
<!-- Place your script tags just before the closing of the body tag. That way, you can be
sure that any HTML element you reference in the script has already been read into memory. -->
<script>
// First, get references to the HTML elements you'll want to work with:
var btn = document.querySelector("button");
var out = document.getElementById("output");
// Then, set up your event handlers in JavaScript, not in HTML
btn.addEventListener("click", getQuote);
function getQuote(){
// Here's a simpler way to set up an array:
var theQuotes= [
'Whenever you see a successful business, someone once made a courageous decision. - Peter Drucker',
'If you\'re not part of the solution, you\'re part of the problem. - African Proverb',
'When you confront a problem you begin to solve it. - Rudy Giuliani',
'Dream of painting and then I paint my dream. - Vincent Van Gogh',
'Be silent or let thy words be worth more than silence. - Pythagoras',
'The past cannot be changed. The future is yet in your power. - Mary Pickford',
'Anything\'s possible if you\'ve got enough nerve. - J.K. Rowling'
];
// You only want your radom number to be from 0 to the amount of the quotes array -1
var quoteNum = Math.floor(Math.random() * theQuotes.length);
// Now, just update the prexisting element:
output.textContent = theQuotes[quoteNum];
}
</script>
</body>
</html>

in short, here is working example:
<body onload="generateRandomQuote()">
<h1>Inspirational Quotes</h1>
<div id="quote-holder" style="font-family: sans-serif; color: red;">
</div>
<div>
<button style="background-color: lightgreen; width:230px; height:70px; border: none; font: bold 25px GreatVibes;" onclick="generateRandomQuote()">Inspire Me More!</button>
</div>
<button style="background-color: blue; width: 200px; height: 70px" onclick="">Share</button>
<img src="images/bg.jpg" id="bg" alt="">
<script>
var quoteHolder = document.getElementById('quote-holder');
var theQuote = [
'Whenever you see a successful business, someone once made a courageous decision. - Peter Drucker',
'If you\'re not part of the solution, you\'re part of the problem. - African Proverb',
'When you confront a problem you begin to solve it. - Rudy Giuliani',
'I dream of painting and then I paint my dream. - Vincent Van Gogh',
'Be silent or let thy words be worth more than silence. - Pythagoras',
'The past cannot be changed. The future is yet in your power. - Mary Pickford',
'Anything\'s possible if you\'ve got enough nerve. - J.K. Rowling'
];
function generateRandomQuote() {
var quoteIndex = Math.floor((Math.random() * theQuote.length));
quoteHolder.innerHTML = theQuote[ quoteIndex ];
}
</script>
</body>
in css you should define units, you had just numbers,
there shouldn't bee any h1 or images or any elements outside your body tag,
it's better to just append your desired content to some div, rather than refreshing the whole page,
...
I see that you already have answer.

Related

Nested text links in HTML

In HTML nested links are not permitted. However, for my purpose (text notes which sometimes refer to whole sentences and sometimes to just one single word within already anotated sentences) I need them. So I have to find a way to solve this problem.
However, all I have now is a basic idea on how it should look and behave. The following mock up shows two links: one to target A, one to B. The "outer" a link is, the lower is the line under it. A is the outer link, thus, its line is lower than that of B. Clicking on the lines of a link should always lead to the target of that link - even if the text above that line is the text of an inner link.
I've tried to show that intended behaviour with hover colors: Blue for A, pink for B.
Any ideas how I could realize this in HTML with the help of CSS (and maybe SVG?). I'd prefer solutions without scripting, but any suggestions are welcomed.
You can use <span>s inside links:
a {color: #00f; border-bottom: 1px solid; text-decoration: none;}
a span {color: #66f; text-decoration: underline;}
Hello, this is link. This is <span>inner link</span> here.
A small problem or extra work is, you need JavaScript to make them follow the links.
But as you asked, you can get the UI Effect without any scripting, but the following of link, definitely needs scripting!
Expanding on the answer from #connexo, you can wrap them all in a span and use a border-bottom on that.
.split-link {
border-bottom:1px solid blue;
padding-bottom:1px; /* for visual reference only */
}
.split-link a {
text-decoration: none;
}
.split-link a.inner-link {
text-decoration: underline;
text-decoration: red;
color:red;
}
<span class="split-link">
Hello, this is a link. It has an
inner link
here.
</span>
You will want to stay within valid HTML, so your only chance (aside of JS) is splitting the outer link into two links.
Hello, this is link. This is inner link here.
.inner-link { color: #66f; text-decoration: underline; }
This will split the blue line in your example into two parts as well, which I assume you do not want. But it's not possible otherwise.
Use JavaScript for best results
I know:
I'd prefer solutions without scripting,
but…
any suggestions are welcomed.
You can add an inline onclick handler to a child span:
AAAA <span onclick="event.preventDefault(); window.location.assign('#B'); return false;">BBBB</span> AAAA
Or, to be DRY, pass in a reference to the handler instead:
AAAA <span onclick="embedLink('#B');">BBBB</span> AAAA
Definition of handler:
function embedLink(url) {
event.preventDefault();
window.location.assign(url);
return false;
}
Working example:
a {
display: inline-block;
text-decoration: none;
color: blue;
border-bottom: 1px solid blue;
padding: 1px;
}
a .annotation {
color: fuchsia;
border-bottom: 1px double fuchsia;
background-color: white;
}
a:hover {
background-color: lightblue;
}
a .annotation:hover {
background-color: lightpink;
}
AAAA <span data-href="#B" class="annotation" onclick="event.preventDefault(); window.location.assign(this.getAttribute('data-href')); return false;">BBBB</span> AAAA
With JS, you can handle other possibilities as well:
Open in new window. Use: window.open() instead of window.location.assign().
Copy to clipboard. Add an event listener to the context and copy events on the parent link. In the handler, use document.execCommand('copy') to grab the url from the clicked child span instead; perhaps its URL is stored in a data-href attribute.
Display URL in status bar. Add a mouseover event listener. In the handler, set window.status = url.
Thank your all for your answers! They all have inspired me!
After some hard thinking and merging your answers together I came to the following solution whose greatest advantage is that the basic functions of all links work without JavaScript.
My main idea is to wrap all links inside a <span> element and, as connexo has suggested, to split up those links which contain links themself. Thus, the HTML skeleton of my above example looks like this:
<span>
<a>AAA</a>
<span><a>BBB</a></span>
<a>AAA</a>
</span>
All JavaScript is associated just with the <span>. Onmouseover, it removes the hover-class from all ancestor <span>. Onclick, it takes the url of the first link child and redirects there.
The CSS is rather simple. It removes the underline from links and defines just how the span should look like (and behave in case of hover).
Another advantage of this design is that nested nested links are also supported, as you can see in the snippet below.
function link_span_click(current_element,current_event)
{
current_event.preventDefault();
current_event.stopPropagation();
var target_href = current_element.getElementsByTagName('a')[0].href;
window.location.assign(target_href);
}
function link_span_mouse_over(current_element)
{
while (current_element)
{
current_element.parentNode.classList.remove('link_span_hover');
current_element = current_element.parentNode;
}
var target_href = current_element.getElementsByTagName('a')[0].href;
window.status = target_href;
}
function link_span_mouse_out(current_element)
{
while (current_element)
{
current_element.parentNode.classList.add('link_span_hover');
current_element = current_element.parentNode;
}
window.status = '';
}
a.nested_link {
text-decoration: none;
}
span.link_span {
cursor: pointer;
display: inline-block;
padding-bottom: 3px;
background-color: white;
border-bottom: 1px solid blue;
}
span.link_span_hover:hover {
background-color: lightblue;
}
<div>
<span
class="link_span link_span_hover"
onclick="link_span_click(this, event)"
onmouseout="link_span_mouse_out(this)"
onmouseover="link_span_mouse_over(this)"
>
AAA
<span
class="link_span link_span_hover"
onclick="link_span_click(this, event)"
onmouseout="link_span_mouse_out(this)"
onmouseover="link_span_mouse_over(this)">
BBB
</span>
AAA
</span>
</div>
<div>
<span
class="link_span link_span_hover"
onclick="link_span_click(this,event)"
onmouseout="link_span_mouse_out (this)"
onmouseover="link_span_mouse_over (this)">
AAA AAA AAA AAA
<span
class="link_span link_span_hover"
onclick="link_span_click(this, event)"
onmouseout="link_span_mouse_out(this)"
onmouseover="link_span_mouse_over(this)">
BBB BBB
<span
class="link_span link_span_hover"
onclick="link_span_click(this, event)"
onmouseout="link_span_mouse_out(this)"
onmouseover="link_span_mouse_over(this)">
CCC
</span>
BBB BBB
</span>
AAA AAA AAA AAA
</span>
</div>
Still, there remains one problem: If a rather long textlink gets split up into to lines only the second (or last to be precise) line gets underlined.

jquery scrollbar plugin conflicts with jquery pagination plugin

first time asking a question here, so thank you in advance and please excuse me if I violate any rules. I'm trying to use this jquery pagination plugin from this site:
http://www.script-tutorials.com/how-to-create-easy-pagination-with-jquery/
and some how it's just not working with the jquery scrollbar plugin I'm using, which is from here:
http://manos.malihu.gr/jquery-custom-content-scroller/
Here's the code I'm working with, you'll see that the scrollbar plugin works on the first page, but after you click on any other subsequent pages it no longer functions:
var Imtech = {};
Imtech.Pager = function() {
this.paragraphsPerPage = 3;
this.currentPage = 1;
this.pagingControlsContainer = '#pagingControls';
this.pagingContainerPath = '#content';
this.numPages = function() {
var numPages = 0;
if (this.paragraphs != null && this.paragraphsPerPage != null) {
numPages = Math.ceil(this.paragraphs.length / this.paragraphsPerPage);
}
return numPages;
};
this.showPage = function(page) {
this.currentPage = page;
var html = '';
this.paragraphs.slice((page-1) * this.paragraphsPerPage,
((page-1)*this.paragraphsPerPage) + this.paragraphsPerPage).each(function() {
html += '<div>' + $(this).html() + '</div>';
});
$(this.pagingContainerPath).html(html);
renderControls(this.pagingControlsContainer, this.currentPage, this.numPages());
}
var renderControls = function(container, currentPage, numPages) {
var pagingControls = 'Page: <ul>';
for (var i = 1; i <= numPages; i++) {
if (i != currentPage) {
pagingControls += '<li>' + i + '</li>';
} else {
pagingControls += '<li>' + i + '</li>';
}
}
pagingControls += '</ul>';
$(container).html(pagingControls);
}
}
.scroll_container {
overflow: auto;
max-height: 100px;
}
body {
background: black;
font-family: Verdana, Helvetica, Arial, sans-serif;
margin: 0;
padding: 0;
color: white;
}
.example {
background: #FFF;
width: 1000px;
font-size: 80%;
border: 1px #000 solid;
margin: 0.5em 10% 0.5em;
padding: 1em 2em 2em;
-moz-border-radius: 3px;
-webkit-border-radius: 3px
}
#content p {
text-indent: 20px;
text-align: justify;
}
#pagingControls ul {
display: inline;
padding-left: 0.5em
}
#pagingControls li {
display: inline;
padding: 0 0.5em
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="assets/imtech_pager.js"></script>
<!-- Add jquery scrollbar plugin -->
<link rel="stylesheet" href="assets/malihu-custom-scrollbar-plugin-master/jquery.mCustomScrollbar.css" />
<script src="assets/malihu-custom-scrollbar-plugin-master/jquery.mCustomScrollbar.min.js"></script>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<section>
<div>
<div class="wrapper">
<h1>Deals</h1>
<div id="content" class="scroll_container scroll">
<div class="z">
Sergey LUKYANENKO - The Boy and the Darkness - Chapter 1. The Sun Kitten.
<h3>Xmas Special Menu</h3>
<div class="button">
Read More
</div>
</div>
<div class="z">
Everything happened because I got ill.
</div>
<div class="z">
It was already two in the afternoon, and I was lying in bed flicking through "Peter Pan" - I must have read it a hundred times over. I had long since pulled off the bandage my mother had tied around my neck in the morning, and thrown it into a corner. I simply can't understand - how can cotton wool soaked in vodka possibly help a cough? I don't argue with my mum, of course, but after she leaves I look after myself in my own way - namely, lie in bed with a book and wait for my germs to get tired of such a boring method of passing time. It usually helps - perhaps not at once, but after a day or three. A good thing, really, that the street outside looked quite miserable - the sun poking out for brief moments, only to make room for a patchy, nasty drizzle. Though, the sun never actually peeked into the room - our house is so unfortunately placed that it is in the shadows of the new nine-floor high-rises on every side. "The only use for such a flat is to grow mushrooms", - dad used to say, back when he still lived with us.
<div>
testing testing testing
</div>
</div>
<div class="z">
I put my book down on the floor next to the bed, and lay on my back. Perhaps, had I shut my eyes now, nothing would have happened. But there I was, lying staring at the ceiling and listening to the ticking of the clock in the hallway.
</div>
<div class="z">
And a speck of sunlight jumped into the room through the glass. Small - the size of my hand - but surprisingly bright. As though the window was open, with bright summer sun outside. Someone was probably playing with a mirror on the balcony of the house across the street.
</div>
<div class="z">
The rabbit floated across the ceiling, climbed down a wall, made a vase on the dressing-table glint, and stopped, shaking slightly, on my headrest.
</div>
<div class="z">
- Don't go, - I said for some reason, knowing that in a moment the mirror would shift and the rabbit would leave my room forever. - Stay...
</div>
<div class="z">
And that's when it all started.
</div>
<div class="z">
The sun rabbit tore free of the bed and floated in the air. I didn't even realise at first that such things don't happen. It was only when the flat spot hanging in the air started puffing out to form a fuzzy orange ball that I understood - a miracle had happened.
</div>
<div class="z">
Four paws stretched from orange glowing fur, followed by a tail and a head. Green cat eyes blinked and gazed at me steadily. And overall, in fact, the rabbit looked more like a kitten than anything else. Except he was hanging in the air, glowing, and seemed light as the fairy fluff that floats away if one blows gently.
</div>
<div class="z">
- Hello, - purred the kitten. - Thank you for the invitation.
</div>
<div class="z">
I closed my eyes for a second, but when I opened them again, the kitten hadn't disappeared. In fact, he'd flown closer.
</div>
<div class="z">
- I don't believe in fairy tales, - I told myself. - I'm grown up now.
</div>
<div class="z">
- Well, compared to the girl who was holding the True Mirror, you are quite grown up, - declared the kitten, unperturbed, and lowered himself onto the blanket. I glanced over - to see if there would be smoke - but everything seemed all right. I could feel warmth with my chest, but not strong. And the kitten tilted his head and added: - But one can't really call you adult, either. How old are you? Ten, maybe?
</div>
<div class="z">
- Fourteen, - I replied, finding myself calming down at such a mundane question. - Who're you?
</div>
<div class="z">
- A sun rabbit, - replied the kitten, examining himself curiously. - What an appearance.. do I look like one?
</div>
<div class="z">
- <b>Like</b> what?
</div>
<div class="z">
- Like a
<p style="font-weight:bold;color:red;">sun</p>
rabbit.
</div>
<div class="z">
- More like a kitten.
</div>
<div class="z">
- Hardly better, - stated the Kitten sadly and stretched out. And I didn't think of anything better than repeating:
</div>
<div class="z">
- Who're you?
</div>
<div class="z">
- But we have already arrived at a consensus! - said the Kitten with sudden hurt. - A sun rabbit, or more precisely - a kitten, because I look far more like one! What is there not to understand?
</div>
<div class="z">
I found myself tongue-tied. Well, naturally, a small green animal that eats stones would simply be - a small green stone-eater. Simple. And a sun rabbit is a sun kitten, because he looks nothing like a rabbit.
</div>
<div class="z">
- So you mean - any rabbit can come to life if one just calls it? - I asked cautiously. For some reason it seemed to me the Kitten would be hurt at the question again. But he just shook his head proudly:
</div>
<div class="z">
- As if! Any! Only True Light, reflected in a True Mirror, can come to life.
</div>
</div>
<div id="pagingControls">
</div>
</div>
</div>
</section>
</body>
<script type="text/javascript">
var pager = new Imtech.Pager();
$(document).ready(function() {
pager.paragraphsPerPage = 5; // set amount elements per page
pager.pagingContainer = $('#content'); // set of main container
pager.paragraphs = $('div.z', pager.pagingContainer); // set of required containers
pager.showPage(1);
$.mCustomScrollbar.defaults.scrollButtons.enable=true; //enable scrolling buttons by default
$(".scroll").mCustomScrollbar({theme:"light-2"}); //I have modified the theme light-2
$(".all-themes-switch a").click(function(e){
e.preventDefault();
var $this=$(this),
rel=$this.attr("rel"),
el=$(".content");
switch(rel){
case "toggle-content":
el.toggleClass("expanded-content");
break;
}
});
});
</script>
</html>
The rest is the files from the malihu jquery-custom-content-scroller
Thanks in advance!
Wrap the #content div within a new div and add the 'scroll_container' class to that. That should work.
jsfiddle
<div class="example">
<h3>Paragraph pagination sample</h3>
<div class="scroll_container">
<div id="content">
<div class="z">Sergey LUKYANENKO - The Boy and the Darkness - Chapter 1. The Sun Kitten.</div>
.....
</div>
</div>
<div id="pagingControls"></div>
</div>

Getting User input with javascript while using three.js?

I am working off of this three.js example (http://threejs.org/examples/#webgl_interactive_cubes) and am trying to find a way for the user to add boxes with specified X, Y, & Z positions.
I could do this with a javascript prompt
var boxes = prompt("X Position", 500); // 500 = Default position
However, I want to make it possible for the user to enter multiple fields (E.g. x, y, z positions; size of box, etc.), so I want to add input boxes. The only way I know how to do this is to use html/css/javascript with something like this -
<!-- CSS formating of Input Boxes -->
<style type = "text/css">
#x_pos {
position: absolute;
bottom: 120px;
left: 10px;
width: 130px;
background-color: #3c4543;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
border: 2px solid #000000;
font-family: Futura;
}
... Repeat for #y_pos & #z_pos
</style>
<!-- Adding a div for each Input Box -->
<div id="x_pos">
<input type="text" id="xpos">
</div>
... Repeat for #y_pos & #z_pos
<h1>Add Node here...</h1>
<!--Allowing user to add input to the Input Box and saving that value as the x, y, & z positions -->
<script text="text/javascript">
var xPosition;
$(document).ready(function(){
$('#xpos').val('Longitude');
$("#xpos").change(function(){
xPosition = $('#xpos').val();
})
... Repeat for #ypos & #zpos
});
However, while I can get the Header and input box to appear, they have absolutely no functionality. I can't type anything in the text boxes and I can't add .click(function () ...) functionality to the h1 text. It's almost like all html and javascript functionality I am used to has been disabled by the rest of the three.js code. My final goal will be to have .click call a function that I can have the divs I defined above appear underneath the h1 "Add Node here..." like this (http://jsfiddle.net/zsfE3/9/).
Can anyone explain to me what is going on here and how I might be able to fix it? Or does anyone have a better way to do this? Thanks guys for any help!
Consinder using the datGUI lib for your project. I had great success with it together with Three.Js. Also there are a number of examples also using it. See this blog post for a tutorial.
Try Something Like This:
html:
<input type = "text" id = "input1">
<button>ADD BOX</button>
</input>
css:
canvas{z-index:-1;}
#input1{
position:fixed;
right:40px;
top:40px;
z-index:1;
width:5%;
height:60px;
}
Good Luck!

Printing global variables in body in Javascript

I'm working with a piece of code I'm designing in my free time, which is a bit unorthodox so bear with me here. The page is set to run a variety of pages based on which "" tag the html is being read from. I was just looking for a way to condense a number of pages into a single one, and this seemed like it might be interesting to mess with. If you guys know of better ways to do that, any information would be appreciated.
So far I'd managed to get everything working until I hit a part where I was trying to obtain a form value, assign it to a global variable, and then use a script to print the global variable in the text. In this case, it is asking the user's name, the goal being to reproduce the name in various places throughout the website for a more user-friendly feel. I figure understanding this will be useful in the future. Eventually I'll want to figure out how to create a database of usernames and passwords and all that good stuff, but for now, I'm just looking for a simple fix. I'm probably missing something elementary. Here's the code:
<head>
<style>
body {
margin: 0 auto;
background-image: URL('http://fc04.deviantart.net/fs9/i/2006/033/2/c/Matrix_code_by_phi_AU.jpg');
background-attachment: fixed;
background-repeat: repeat-y;
}
</style>
<meta charset="utf-8">
<title>MasterCode</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
var name = "";
//user is "finished typing," collect input
function doneTyping() {
name = document.getElementById('nameid').value;
closeElement('welcomepage');
closeElement('namepage');
showElement('homepage');
}
function closeElement(myelement) {
document.getElementById(myelement).style.display = "none";
}
function showElement(myelement) {
document.getElementById(myelement).style.display = 'block';
}
function enterWebsite() {
closeElement('namepage');
closeElement('homepage');
$("#dialog").dialog({
autoOpen: false
}, {
title: "Change"
}, {
resizable: false
});
$("#opener").click(function () {
$("#dialog").dialog("open");
closeElement('welcomepage');
showElement('namepage');
})
}
function writeName() {
document.write(name);
}
</script>
</head>
<body onload="enterWebsite()">
<div id="welcomepage">
<button id="opener" style='background: url("http://4.bp.blogspot.com/-fDgJmT5rzlM/Tq8SpW3ZcbI/AAAAAAAAA1I/l02iiclqKkA/s1600/tracking%2Bclub%2Bmeet%2B%2526%2BMisty%2BAlgonquin%2Bshots%2B106.jpg") no-repeat top left; color: #FFFFFF; height: 685px; width: 1350px; font: 75px helvetica, cursive'>Enter MasterCode</button>
</div>
<div id="namepage">
<form id='name_input'>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<center>
<input style="background-image:URL('https://waypointprod.blob.core.windows.net/blogfilestore/storage/blogs/headlines/2013/12/5/image.jpg');background-repeat:no-repeat;background-position: ; border: 50px solid black ; height:50px; width:350px; color: #FFFFFF; font: 45px helvetica, cursive;"
id='nameid' type="text" value="Enter your name.">
<br/>
<button id='submit_name' onclick='doneTyping(); return false;'>I Accept The Risks</button>
</form>
</div>
<div id="homepage">
<font size="25" color="white">
Welcome, <script> writeName(); </script>
</font>
</div>
</body>
</html>
Thoughts?
(Edit: Resolved using localStorage as suggested by tewathia)
Not sure if you're using any sort of RESTful API or even nodejs.
If you are, something I do to prevent storing this data in cookie or in sessionStorage is that I utilize server-side to store. Then you wouldn't need to add as much logic on client-side. This user data could be
{
"name": "Don Jon",
"favorite_color": "blue"
}
you could even display different parts of the page in blue to be super user friendly

Sort sibling <div>s with jQuery

I'm banging my head with the problem that has more to do with 2nd grade mathematics than programming. Here goes: four <div> elements are placed one after another, horizontally. When you click one, script places it in front. You click another one, and it's also placed in front, etc. You get the picture. Now, what I'd like to do is to sort remaining <div> elements (all but the first one) using original order.
Maybe this pic will make things clear:
After step #3, C should be placed after B, so it should go like this: D A B C.
Here's a sample code:
<html>
<head>
<title>mixit</title>
<style type="text/css">
.insidebox{
width: 50px;
height: 50px;
line-height: 50px;
margin: 0 0 0 20px;
text-align: center;
float: left;
border: black solid 3px;
font-family: sans-serif;
cursor: pointer;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<div id="container">
<div id="a" class="insidebox">A</div>
<div id="b" class="insidebox">B</div>
<div id="c" class="insidebox">C</div>
<div id="d" class="insidebox">D</div>
</div>
</body>
</html>
Now, I understand that I can use .insertAfter() to place element in front, but how should I tackle the sorting part? The keyword is initial order, not alphabetical order. Letters and boxes are given just for illustrative purposes.
This should do what you want.
var $initial = $('.insidebox');
$('.insidebox').click(function(){
var $this = $(this);
$this.parent()
.prepend($this)
.append( $initial.not(this) );
});
You store the initial list and on each click re append it (excluding the current one)
demo http://jsfiddle.net/gaby/Dyafx/
update
Hell.. you do not even need to prepend the current element.. when you append the rest they will go after the clicked one anyway ..
var $initial = $('.insidebox');
$('.insidebox').click(function(){
$(this).parent()
.append( $initial.not(this) );
});
demo http://jsfiddle.net/gaby/Dyafx/1/
Store the initial order as an array. Then sort by array index- the first one (A) will have array index 1, etc.
Do this:
$(document).ready(function(){
$("#container div").click(function(){
$(this).prependTo($(this).parent());
});
});
cheers.

Categories

Resources