Show random div onclick - javascript

I am making a little project. For this project I want to be able to show a div to visitors of my site. However, I want my content to be varying. I've created three divs, all with a different id. When someone enters my site, I want him/her to see just one of the three divs. I've created some code that I thought would do the trick, but obviously it did not. I would really appreciate it if someone could tell me where I'm doing it wrong.
HTML
<div id="one">
1
</div>
<div id="two">
2
</div>
<div id="three">
3
</div>
<input type="button" id="Button" value="Random" onclick="RandomDiv();" />
CSS
#one {
display:none;
}
#two {
display:none;
}
#three {
display:none;
}
JAVASCRIPT
function RandomDiv() {
var myarray= new Array("one","two","three");
var ChosenDiv = myarray[Math.floor(Math.random() * myarray.length)];
alert(ChosenDiv); //Just to show this.
document.getElementbyId(ChosenDiv).style.display="inline-block";
}
Now, the alert seems to work fine, so that means that there is no problem in deciding the "ChosenDiv" (one, two or three). However, when I want to make that chosen div visible (display:none -> display:inline-block), it simply won't do this. I tried to use Google Chrome for defining the problem, but I can't tell what the problem is.

Why do answers always have to be so overcomplicated?
Just run the code, check your console and find out that you're using getElementbyId and not getElementById with a capital b, it's basic problem solving?
TypeError: document.getElementbyId is not a function[Learn More] script.js:6:5
jQuery is way to much to put into your project to simply edit some CSS or select some simple elements, if you ask me.

Using jQuery can help with changing CSS in javascript.
See http://api.jquery.com/css/ for more information on how to use this.
function RandomDiv() {
var myarray= new Array("one","two","three");
var ChosenDiv = myarray[Math.floor(Math.random() * myarray.length)];
alert(ChosenDiv); //Just to show this.
document.getElementById(ChosenDiv).css("display":"inline-block");
}
Don't forget to include jQuery in your code!
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>

Just use a new function to call the display, lumping it in with your randomiser is one way to get a whole mess of bugs, and as previously mentioned, it seems you need to check your capitalisation, it's important

You could convert values in your array to this format:
var myarray= new Array("#one","#two","#three");

Related

How to add user input to a JavaScript array

I am in the process of learning JavaScript and jQuery, so apologies if any of this sounds naive or obvious. I started what I thought was a fairly simple project to practice and hopefully learn something in the process.
What I want to do is this: the user inputs a sentence and hits a submit button. The sentence gets added to a list of other sentences submitted by people (preferably on a separate file, preferably encrypted, but not necessary). Then, the website grabs a random sentence from the list and displays it.
I am not asking on how to build all of this. I have already put most of it together, but I am including it here for reference.
I have a separate javascript file with the array of quotes.
var quotes=new Array();
quotes[0]="<p>Quote 1</p>";
quotes[1]="<p>Quote 2</p>";
quotes[2]="<p>Quote 3</p>";
quotes[3]="<p>Quote 4</p>";
quotes[4]="<p>Quote 5</p>";
quotes[5]="<p>Quote 6</p>";
quotes[6]="<p>Quote 7</p>";
Then I randomly display one using this:
function getQuote(){
var thisquote=Math.floor(Math.random()*(quotes.length));
document.write(quotes[thisquote]);
}
And adding <script> getQuote(); </script> to the html.
This all works fine.
The part I cannot seem to figure out is taking user input and adding it to the jQuery array. I am using a contenteditable div instead of an <input> because I want it to have multiple lines of text and have a character limit, which as far as I know can only be done with a contenteditable div (according to the research I did at the time, I may be wrong).
I have looked around and tried many if not all the examples I found of how to do this, and none of them worked. This is the last method I tried, if it helps:
$(".submit").click(function() {
quotes[quotes.length] = document.getElementsByClassName("input").value;
});
So, to reiterate, I want to take user input and add it to a JavaScript array. I have scoured stackoverflow and the interet but nothing has worked. Please help!
UPDATE: Arvind got it right. I still have a lot to learn, and it seems I need to read up on localstorage and cookies. I will also need to use PHP to save the sentences on the server. Thank you to all who answered!
Problem is document.getElementsByClassName("input") gives you a NodeList and not just a single html element. So if you do this document.getElementsByClassName("input").value, you will end up quotes as [undefined, undefined ... undefined]. Assuming you have single element with the class name input, go with index 0. Also as you stated that you are using div with attribute contenteditable, you may try this instead. document.getElementsByClassName("input")[0].innerHTML
Try this example.
var quotes = localStorage.getItem('quotes'); //get old, if any, gives you string
quotes = quotes ? [quotes] : []; // if got quotes then make it as array else make new array
$(function() {
var quote = $('#quote'); //get the quote div
quote.html(quotes.join('') || quote.html()); //set the default text
$('#btn').on('click', function(e) {
quotes.push(quote.html());
localStorage.setItem('quotes', quotes.join('')); //save the quotes
alert(quotes.join(''));
});
});
#quote {
border: 1px solid grey;
height: 100px;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div contenteditable='' id='quote'>
<ol>
<li>Quote 1</li>
<li>Quote 2</li>
</ol>
</div>
<input type='button' id='btn' value='Submit' />
P.S.
In order to preserve the old quotes you may possibly use cookie, localStorage, etc.
Are these "quotes" being saved locally?
Yes, to share it among several users visiting by different browsers, you have to save it with the server script like PHP, Java, ASP, etc. Here you can either use ajax, if you wana avoid page reload on submit, else you can go for form submit.
$(".submit").click(function() {
quotes[quotes.length] = document.getElementsByClassName("input").value;
});
should be
$(".submit").click(function() {
quotes.push(document.getElementsByClassName("input").text());
});
EDIT: With a content editable div you need to use text() instead. Here is an example fiddle. https://jsfiddle.net/
var quotes=[];// better
// function to add to array
function addQuote(myquote){
quotes.push('<p>'+myquote+'</p>');
}
addQuote("Quote 1");
addQuote("Quote 2");
addQuote("Quote 3");
addQuote("Quote 4");
addQuote("Quote 5");
addQuote("Quote 6");
addQuote("Quote 7");
addQuote("Quote 8");
$(".submit").on('click',function() {
addQuote(document.getElementsByClassName("input")[0].value);
});
NOTE: suggest NOT using the "input" class name and use some other one as that might be confusing to others at some point later (confused by element named input)
I also added the paragraph tags as that would provide a consistent pattern for your input text. Assumption on my part however.
NOTE I also assume that the element IS an input type with the .value since that is NOT provided (the markup)

JQuery Cookies with dynamic div ID's

I hope you guys can give me a push in the right direction as this problem has been eating me up all day now..
What I'm basicly trying to accomplish is this. I have several div's on a page that can be collapsed independently from eachother with the use of a button. Every div has it's own specific ID, generated with a string of static text, and a numeric value based on a auto-incremented database-value. This ensures I never have two div's with the same ID on one page. To target each specific div with Javascript (jQuery) I use the following code:
http://jsfiddle.net/LU7QA/0/
This works really well and does what it's supposed to do. Only there is one problem. On every page frefresh, every div that was opened is closed. Everything resets, and that's why I want to use JQuery Cookies in this construction. Only problem is, I know how it works, but I can't get it to work in this specific construction as it has to deal with a completely unique ID every time and needs to store the values of that particular ID.
As seen here: http://jsfiddle.net/LU7QA/1/
I tried to fiddle around with it but I can't seem to get it working properly and I'm starting to lose my sight on the problem..
<div>
<button class="button_slide" value="1">Show hide</button>
</div>
<div id="slidingDiv_1" class="slidingDiv">Stuff</div>
<div>
<button class="button_slide" value="2">Show hide</button>
</div>
<div id="slidingDiv_2" class="slidingDiv">Stuff</div>
function initMenu() {
$(".slidingDiv").hide();
// Toggle Field
$(".button_slide").click(function(){
//alert($(this).val()); debugging purposes
var sliding_id = $(this).val();
div_sliding_id = '#slidingDiv_'+sliding_id;
$(div_sliding_id).next().slideToggle('slow', function() {
$.cookie(div_sliding_id, $(this).is(':hidden') ? "closed" : "open");
return false;
});
});
$('.button_slide').each(function() {
var sliding_id = $(this).val();
div_sliding_id = '#slidingDiv_'+sliding_id;
if ($.cookie(div_sliding_id) == "open") $(this).next().show();
});
}
jQuery(document).ready(function() {initMenu();});
May you have missed a dot on the last *button_slide* declaration?
Btw, look at https://code.google.com/p/sessionstorage/

How to remove a class via JavaScript (NOT jQuery) at Wordpress

I need your help at a problem of my Wordpress Webpage. My Wordpress-page is an Single-Page-App with 3 different boxes of content. The left and center boxes are static, the right one changes its content by clicking on links of the other boxes. I decided, to load all the content in the right box and show them with the CSS-command visibility. With a combination of pathJS and JS, i want the URL to change by clicking on the links. So far so good - all works fine, but i dont get managed via my JS-Function to remove the shown-class.
My script looks like this:
<script>
function showDetailContent(showid) {
//suche objekt right_id -> was du zeigen willst -> getelementbyid
alert("1");
var id = document.getElementsByClassName('shown');
alert("2");
id.classList.remove('shown');
alert("3");
document.getElementByID("right_" + showid).classList.add('shown');
alert("4");
}
//var c = document.getElementById('content'); -->do the function :)
Path.map("#/?p=<?php the_id();?>").to(function () {
showDetailContent(<?php the_id();?>);
});
Path.listen();
</script>
The alerts are just my way of "debugging". I think its not the best way to debugg, but i am very new in the world of prorgamming and this is kind of easy.
However, the first two alerts are shown, if i activate a link. So the (first) mistake is on the line
id.classList.remove('shown');
Normally, the right-box is hidden, so that only one content is load.
Do you understand my problem till here?
I would appreciate fast help!
Greetings, Yannic! :)
Look at this : http://snipplr.com/view/3561/ to know remove class pure javascript
getElementsByClassName gets multiple elements, try:
var id = document.getElementsByClassName('shown')[0];
Or iterate through them if you want to remove class from all elements with class shown;

How do I compare css style values using JavaScript if conditions?

I got a quick question. If I want to compare a style left / right value with another coordinates (lets say mouse) how do I do it?
Here is what I tried without mouse coordinates but for some reason my condition never executes...
<style>
#container
{
position:absolute;
left:400px;
top:200px;
}
</style>
<script>
function moveExit(){
var containerId = document.getElementById("container").style;
if(containerId.left == 400 + "px")
containerId.left = 395 + "px";
}
</script>
And here is my body:
<body>
<div id="container">
<img
src="Images/image.jpg"
onmouseover="moveExit();"
/>
</div>
</body>
This is my first time playing around with javascript.. Thanks!
you need to use computed style for this purpose.
How do I get a computed style?
var left = window.getComputedStyle(document.getElementById("container")).left
for IE8 you have to use currentStyle proeprty as computed style is not supported.
document.getElementById("container").currentStyle.left
Cross-browser (IE8-) getComputedStyle with Javascript?
Try something like this:
http://jsfiddle.net/xtJA4/
$(document).ready( function() {
$("#container").mouseleave(function() {
if ($(this).css("left")=="400px") {
alert("Left = 400px");
}
});
});
There are of course changes that can be made to this, but for what you're needing this should work fine. You can of course go and change the alert() function to match what you need (modifying the left offset), but hopefully this helps!
While I'm not 100% sure what exactly you are looking to accomplish, here are a few comments, and suggestions for your code.
Rather than user javascript, I would use jQuery. This is something that David has suggested previously. One of the great advantages of jQuery is that it gets around most browser incompatibility issues.
To do this with jQuery you'll need to import jquery, and then you can use it like so:
<script type="text/javascript" src="./jquery/jquery.js"></script>
<script type="text/javascript">
function moveExit(){
var $element = jQuery('#container');
$element.css('left', '350px');
}
</script>
Please also notice that I have added the "type" attribute to the script elements.
As a side-note I would also remind you to add "alt" attributes to img elements. Good for accessibility and for when the images are blocked for whatever reason.
With greater understanding about what you are trying to accomplish a better answer can be provided.

Create own numpad with inputs

I've been searching the web for some tips regarding how to make your own numpad, created with html code, to act as a numpad would on the computer.
I have this numpad on my website that would give an input to a textfield in the same div. I've given a value to each button and now I guess I would have to create something more so that the numbers will add to my text field.
I'm really a beginner with programming so maybe this is really easy. Thanks for the help!
You could do it, alternatively, with jQuery. jQuery is better IMHO if you need a simple easy solution (jQuery is generally easier and faster).
HTML:
<div id="myDiv"> </div> //the div to which we add text
<div id="buttonContainer"> //this is the div containing the numbers (the numpad)
<button value="one"> one </button>
<button value="two"> two </button>
</div>
jQuery:
$("#buttonContainer button").click(function() {
$("#myDiv").append($(this).val());
});
http://jsfiddle.net/DLzUU/1/
What this does is: when you click any button inside the div with id of 'buttonContainer', it adds its value to the div with the id of "myDiv".
On the Javascript subject, if you want a VERY good guide: http://javascript.info/
what you need is to learn javascript. With javascript you will be able to write code to do this.
<script>
function AddValueToTextField(val)
{
document.getElementByID( <textfiled ID> ).value += val;
}
</script>
<button onClick="AddValueToTextField(this.value)"></button>
this is only very basic but it is a rough idea of what is needed, the button is set to call the function "AddValueToTextField" when it is clicked. When the function is called the value of the button is sent along with it. Inside the function it gets a handle on the textfield and adds the value of the button to whatever was already there, I'd suggest looking at:
http://www.w3schools.com/js/
as a place to start learning javascript.
you can try http://keith-wood.name/keypad.htmlkeypad example, this is an awesome example
$(document).ready(function(){
var selected;
$(".admin_loginid input").focus(function(){
selected = $(this);
});
$(".loginbtn").click(function(){
selected.val(selected.val() + $(this).val());
});
});
Solved it that way and it works really well, thanks for the help! Now my selected input box takes the input from the numpad that i've created.

Categories