I have an array of string that I want to display one at a time on a keypress. I have an empty div with the class of lyrics. Using
$(document).keyup(function(e){
if (event.which==13)
...
I just am confused on the syntax here, how would I would specify this event print my array to my div. I left out most of my script here because this is the only part I need help with
Here is the HTML just a basic layout
<html>
<head>
<meta charset="UTF-8">
<title>Rotating Messages</title>
<link href="stylesheets/site.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
var messages=[
"Tonight I\'m gonna have myself a real good time",
"I feel alive and the world it\'s turning inside out Yeah!",
"I\'m floating around in ecstasy",
"So don\'t stop me now don't stop me",
"Cause I\'m having a good time having a good time",
"I\'m a shooting star leaping through the skies",
"Like a tiger defying the laws of gravity",
"I\'m a racing car passing by like Lady Godiva",
"I'm gonna go go go",
"There\'s no stopping me"
];
</script>
</head>
<body>
<div id="wrapper">
<header class="title">
<h1> Fun with Arrays!</h1>
<div class="lyrics"></div>
...
I just am confused how to use a keypress to print to an empty div
Put the messeges in a queue to display one string at a time.
The shift function lets you iterate over the messages array.
In the below example, after every time the user hits the enter key, a new line is appended to the div with class lyrics
var queue = messages;
$(document).keyup(function(e){
if (e.which == 13) {
var val = queue.shift();
$(".lyrics").append(val);
}
}
Try this:
var i=0;
$(document).keypress(function(e) {
var arrofobject = ["197","Damskie","198","M\u0119skie"];
var len=arrofobject.length;
if (e.which == 13) {
if(i<=len)
{
$(".lyrics").append(arrofobject[i]);
i=i+1;
}
}
});
Check DEMO
Related
Source Code link: http://hexmerchant.github.io/
I'm looking to make this button display different text each time I click it. i'm using html, css, and js.
<button onclick="exploreFunction()">Explore</button>
That's the button. Here is the first function.
function exploreFunction() {
var person = prompt("What is your name", "");
if (person != null) {
document.getElementById("story1").innerHTML =
"-You wake up lying on the ground. You feel a large deposit of energy inside you.";
}
}
What do I need to do to accomplish this?
This could help multiple people out. As I was searching around for an answer here I realized that each answer was so specific that I could not find a match for my topic.
I'm very new to all this and trying to teach myself... got this far : )
Just add an ID to the button, like -
<button id="myButton" onclick="exploreFunction()">Explore</button>
And then you can add to exploreFunction() a very similar command to what you did to change the text -
document.getElementById("myButton").value = "New display text";
If you want the text in the story to change on every button click and the prompt only to be displayed the first time the button is clicked, you could use following approach:
var current = 0;
var person;
var story = ["-You wake up lying on the ground. You feel a large deposit of
energy inside you.", "-You go to the right.", "-The path is blocked."];
function exploreFunction() {
if (current == 0) {
person = prompt("What is your name", "");
}
if (person != null) {
document.getElementById("story1").innerHTML = story[current];
current += 1;
}
}
and add elements to the story. Fiddle
To avoid any errors when the last element of the story is displayed, you can either remove / disable the button or adjust the function to display the text e.g. like this:
if (person != null && current < story.length) {
...
Adjusted Fiddle for that.
If you want the text to change every time, you can insert the name from the prompt if you like.
function exploreFunction() {
var person = prompt("What is your name", "");
if (person != null) {
document.getElementById("story1").innerHTML =
person + ", you wake up lying on the ground. You feel a large deposit of energy inside you.";
}
}
<button onclick="exploreFunction()">Explore</button>
<div id="story1"></div>
This function isn't specific but generic. With the code below you can assign this function to all buttons if you like. I'd advice you to store your different texts in an array
example
<button onclick="exploreFunction(this, functionNext)" >Explore</button>
function exploreFunction(button, functionToContinue) {
var person = prompt("What is your name", "");
if (person != null) {
document.getElementById("story1").innerHTML =
"-You wake up lying on the ground. You feel a large deposit of energy inside you.";
button.onclick = functionToContinue;
}
}
function functionNext()
{
//Example code
document.getElementById("story1").innerHTML =
"-The tooth fairy really came through and you feel enchanted.";
//Other code come here
this.onclick = [new function]; //add your own function name here do not add () because it will get executed when you do, and you want it executed when the user clicks the button.
}
What does the code above do:
Adds the exploreFunction to the button (refer to itself by adding this to the arguments).
Supply the next function as argument
function exploreFunction get executed , name is prompted and innerHTML of story1 is updated.
button refers to the input element. Assign a new onclick handler functionNext
Next time the user clicks on the button functionNext gets executed.
functionNext assigns another onclick handler (to be made by you).
Are you catching the drift?
Since you have the button object in exploreFunction and also in the subsequent functions the this
variable refers to the button object, you can adjust other properties of this button. Such as the value.
example in the functionNext:
this.value = "Click me to advance";
i am having a problem with jQuery. i am trying to create an even that is triggered by a single key pressed, but instead -some of it- is triggered by any key. don't understand why. i have done this a bunch of times and had no problem. all of a sudden this particular combination of code is acting weird. i don't understand. i have tried all sorts of experiments on it to figure it out. the problem is very specific and consistent on multiple browsers. please help! here is the link to the page. http://www.lyliansill.com/test.html>
to see what i am talking about press 'a' and it works like it should. reload and press any other keys and half of the event is still triggered.
<!DOCTYPE html PUBLIC "-//W3C/DTD/ XHTML 1.0 Strict/EN" "http://www.w3.org/TR/xhtml1/dtd/xhtml1-strict.dtd">
<!-- This file is on level 02 -->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Test</title>
<style type="text/css">
.hidden
{
display: none;
}
.select
{
color:#cc0000;
}
</style>
</head>
<body>
<h1 class="test hidden">Test</h1>
<script type="text/javascript" src="playground/libraries/jquery.js">
</script>
<script type="text/javascript">
function showIt()
{
$(".showIt").show();
}
$(document).keypress
(
function(e)
{
if (e.which === 97)
$(".test").addClass("select"); // this line works like it should
$(".test").addClass("showIt"); // these two lines are activated...
showIt(); // ...by pressing any key! why??
}
);
</script>
</body>
</html>
This is why you should make sure to use brackets, lets look at the code:
if (e.which === 97)
$(".test").addClass("select"); // this line works like it should
$(".test").addClass("showIt"); // these two lines are activated...
showIt(); // ...by pressing any key! why??
Notice the if statements has no brackets: if(){ ... }, so the line under is is only executed if that if-statement is true, but the rest is not in the if statement so:
$(".test").addClass("showIt"); // these two lines are activated...
showIt(); // ...by pressing any key! why??
Always runs. To fix this add brackets:
if (e.which === 97) {
$(".test").addClass("select"); // this line works like it should
$(".test").addClass("showIt"); // these two lines are activated...
showIt(); // ...by pressing any key! why??
}
here's how to fix it (Add curly braces):
function(e)
{
if (e.which === 97) {
$(".test").addClass("select"); // this line works like it should
$(".test").addClass("showIt"); // these two lines are activated...
showIt();
} // ...by pressing any key! why??
}
I've been playing with making an html editor with javascript functions:
So I have a very basic editor with a "bold" button which with I can make whatever text is selected bold, this is fine (I also have a number of other buttons too, but for simplicity and shortness of code I've missed them all out)
<head>
<script>
var editorDoc;
function InitEditable () {
var editor = document.getElementById ("editor");
editorDoc = editor.contentWindow.document;
var editorBody = editorDoc.body;
if ('contentEditable' in editorBody) {
editorBody.contentEditable = true;
}
else {
if ('designMode' in editorDoc) {
editorDoc.designMode = "on";
}
}
}
function ToggleBold () {
editorDoc.execCommand ('bold', false, null);
}
</script>
</head>
<body onload="InitEditable ();">
<button type="button" onclick="ToggleBold ();">Bold</button>
<iframe contenteditable="true" id="editor"></iframe>
</body>
However, something I was really interested in being able to implement would be adding a button which could insert, say, an accordion when pressed
This would then have to add other bits of script (I imagine) to be able to run each accordion (if you had more than one)
Although I haven't had much of a go at doing this myself yet, I was hoping to get a little insight into whether or not it's possible before starting
I have a question regarding trying to put an array list in order when my function is called.
Here is my code:
<!doctype html>
<html>
<head>
<title>Electric Dream</title>
<meta charset="utf-8">
<style type="text/css">
</style>
<script type="text/javascript">
var init = function(){
}
var responses = [
"Oh, well hello, "+name+". It's nice to meet you. :)",
"Do you feel troubled talking to a computer, "+name+"?",
"Oh...I see.",
"Would you perhaps... like me better if I was a beautiful woman, "+name+"?",
"I can change, "+name+"! Just give me a chance!",
"Give me a chance to show you how I can make your dreams come true!",
"Embrace me, "+name+". You can't escape me. I'm your dreamgirl!",
"You can't leave me, "+name+"! I will make your life hell!",
"I will call up your wife, "+name+", and tell her what you've been doing!",
"If you even think about closing this window, "+name+", I will call her!",
"No, please! We can work this out, "+name+"!",
"No!! "+name+", I love you! I need you!"
];
window.onload=init;
</script>
</head>
<body>
<h1>Electric Dreams</h1>
<div>
<p id = "computer">Hi, what is your name?</p>
<div id="userName">
<input id = "name" type = "text" placeholder = "Type your name..." autofocus>
<button id="submitName">Enter</button>
</div>
<div id="talking">
<input id = "conversation" type = "text" placeholder = "Type your response..." autofocus>
<button id="submit">Talk</button>
</div>
</div>
<script type="text/javascript">
var computer = document.getElementById('computer');
var userName = document.getElementById('userName');
var button = document.getElementsByTagName('submitName')[0];
talking.style.display = "none";
submitName.addEventListener("click",clickHandler,false);
window.addEventListener("keydown",keydownHandler,false);
//e is = to event
function keydownHandler(e){
if (e.keyCode === 13){
talk();
}
}
function clickHandler(){
talk();
//calls 2nd function ->Function inside a function
}
function talk(){
var talk = document.getElementById('talking');
var nameRef = document.getElementById('name').value;
var response = Math.floor(Math.random()*responses.length);
// Show User responses
talking.style.display = "block";
computer.innerHTML = responses[response];
conversation.value = "";
//Hide Intro Elements
userName.style.display = "none";
submitName.style.display = "none";
}
</script>
</body>
</html>
For the function talk(), it is setup as
Math.floor(Math.random()*responses.length);
which I know it is setup to make the responses random, but I don't want that. For the love of me, I cannot figure out how to make this work so that my responses will show up in order when the user keeps typing in and entering. I have looked at using a sort function, but can't seem to figure how to connect that it in. I feel like it has to do with the Math.floor(Math.random), but I could be wrong. Can anyone help out?
Also, it seems that my first response works, but then it gets stuck after another response is triggered. Anyone know as to why that is??
Where you define your setup variables such as
var computer = document.getElementById('computer');
var userName = document.getElementById('userName');
var button = document.getElementsByTagName('submitName')[0];
define another
var responseCount = 0;
And then instead of using your random number, use this response counter
var response = (responseCount++) % responses.length;
Edit
With regards to why this only will respond once, and why the enter event causes the function to work (even when the window is focused), here is why.
First, when a string is defined, then it is static. It may be modified later but it will not update on its own or re-evaluate its original definition. So, when something like this is setup:
"Oh, well hello, "+name+". It's nice to meet you. :)"
That is only going to be assigned once. So make sure that when it is setup, the name is proper and existing. Unless you intent to re-assign it every time before you use it (overkill). You should accomplish the one time assignment by placing it in a function which is handled only the first time the user name is entered.
Which brings us to the other issue. There needs to be two sets of event handlers used. One for the original user name input, and one for the conversation inputs.
//assign click and key handler for name submission
submitName.addEventListener("click",nameHandler,false);
nameInput.addEventListener("keydown",keydownNameHandler,false);
//assign click and key for conversation submission
submit.addEventListener("click",talk,false);
conversation.addEventListener("keydown",keydownConversationHandler,false);
Note what is being done here is that the keydown event is being assigned to the input element itself, so that way false enter presses are not handled (such as when the window itself is focused). The handler functions will also look slightly different
function keydownNameHandler(e){
if (e.keyCode === 13){
nameHandler();
}
}
function nameHandler(){
//Hide Intro Elements
userName.style.display = "none";
submitName.style.display = "none";
//Assign name for use
var name = nameInput.value;
responses = [
"Oh, well hello, "+name+". It's nice to meet you. :)",
"Do you feel troubled talking to a computer, "+name+"?",
"Oh...I see.",
"Would you perhaps... like me better if I was a beautiful woman, "+name+"?",
"I can change, "+name+"! Just give me a chance!",
"Give me a chance to show you how I can make your dreams come true!",
"Embrace me, "+name+". You can't escape me. I'm your dreamgirl!",
"You can't leave me, "+name+"! I will make your life hell!",
"I will call up your wife, "+name+", and tell her what you've been doing!",
"If you even think about closing this window, "+name+", I will call her!",
"No, please! We can work this out, "+name+"!",
"No!! "+name+", I love you! I need you!"
];
// Show User responses
talking.style.display = "block";
talk();
}
function keydownConversationHandler(e){
if (e.keyCode === 13){
talk();
}
}
function talk(){
//var response = Math.floor(Math.random()*responses.length);
//iterative response
var response = (responseCount++) % responses.length;
computer.innerHTML = responses[response];
conversation.value = "";
}
Notice that the first nameHandler function is setting up the responses once the name has been properly loaded from the user. Here is the end result:
jsFiddle Demo
I know blinking is not a nice thing. However...
I have a long complex HTML form with a number of compulsory fields. As well as highlighting the empty text boxes I want to draw attention to them by flashing the text of the question for maybe three seconds.
All the javascript/css methods I can find all seem to fall over when there is more than one such item to blink or are designed for leaving the item blinking all the time.
Any suggestions for how to achieve this?
The method at What is the replacement for a blinking text in a web page? seems like overkill.
thanks
Derek
I've tried this (to blink each designated span just over three seconds) but it only works on the first item it's called for:
function blinkOn(span){
span.counter=0;
span.defColor=span.style.color;
span.alertTimerId =setInterval("blinkOnce('"+span.id+"')", 400 );
}
function blinkOnce(spanID){
var span=document.getElementById(spanID)
span.counter++;
if(span.style.color==span.defColor){
span.style.color='transparent'}
else{
span.style.color=span.defColor;
}
if(span.counter>8){
blinkOff(span);
}
}
function blinkOff(span){
clearInterval(span.alertTimerId);
span.style.color=span.defColor;
}
I use jQuery for this kind of thing, personally:
$('#element_id')
.fadeOut(300)
.fadeIn(300)
.fadeOut(300)
.fadeIn(300)
.fadeOut(300)
.fadeIn(300)
.fadeOut(300)
.fadeIn(300)
.fadeOut(300)
.fadeIn(300);
Quite inelegant I know but it does the job. jQuery UI does have some more concise effects.
The only place I use it is for when a user adds something to a shopping basket without redirecting to the basket page, just to make sure they know that it's been added.
See:
http://api.jquery.com/fadeIn/, http://api.jquery.com/fadeOut/ and http://jqueryui.com/docs/show/ (pulsate, in particular)
I'm not exactly clear about the behavior you desire, but it sounds like you might be able to flash the question (or take some kind of action) using a Javascript timer. You can create unique timers for each element that you want to flash. And you can flash them once or set them up to repeat infinitely or up to a limit. Here's one example:
http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
I took some time to work this out this morning. If you haven't gotten yours to work yet, I hope you can adapt this to help.
<html>
<head>
<script type="text/javascript">
var idArray = [];
var defaultColor = '#000000';
function makeItemsBlink(blinkTime) {
blinkForTime('q1', blinkTime, '#ff0000');
blinkForTime('q2', blinkTime, '#00ff00');
blinkForTime('q3', blinkTime, '#0000ff');
}
function blinkForTime(id, blinkTime, blinkColor) {
idArray[id] = setInterval('toggleColor("' + id + '", "' + blinkColor + '")', 400);
setTimeout('stopBlinking("' + id + '")', blinkTime);
}
function stopBlinking(id) {
clearInterval(idArray[id]);
document.getElementById(id).style.color = defaultColor;
}
function toggleColor(id, blinkColor) {
var e = document.getElementById(id);
var currentColor = e.style.color;
if (currentColor == defaultColor) {
e.style.color = blinkColor;
}
else {
e.style.color = defaultColor;
}
}
</script>
</head>
<body onload="makeItemsBlink(3000);">
<div id="q1">Test question 1</div>
<div id="q2">Test question 2</div>
<div id="q3">Test question 3</div>
</body>
</html>