Change text color with Select/Option - javascript

I'm trying to change a text color, using the Select object, trying to get the color I selected and setting it to the text. There are two functions commented on my script, both were my attempts to get it done, but failed. Not asking for a complete answer/code, just want to know what is wrong.
This is the code and thanks for your time:
<!DOCTYPE HTML>
<html>
<head>
<title>Hola Mundo Controles</title>
<meta name="author" content="José Del Valle Cordero"/>
<meta charset="utf-8" />
</head>
<body>
<div class="main">
<div class="subject" id="subject">
<span id="salute">¡Hello!</span>
</div>
<div id="control">
<div class="color_option">
Color:
<select name="color_list" id="colors" >
<option value="cl_option1" checked="checked">Red </option>
<option value="cl_option2">Blue </option>
<option value="cl_option3">Yellow </option>
<option value="cl_option4">Black </option>
</select>
</div>
</div>
</div>
<script type="text/javascript">
var item,cl;
var colorsMap = {
'cl_option1' : "red",
'cl_option2' : "blue",
'cl_option3' : "yellow",
'cl_option4' : "black"
};
/*colors.onchange=function() {
var salute = document.getElementById("salute");
var item = document.getElementById("colors").selectedIndex;
var color = colorsMap[item];
salute.style.color = color;
};*/
/*$('#colors').change(function(){
var salute = document.getElementById("salute");
item=$(this).val();
cl = colorsMap[item];
salute.style.color = cl;
});*/
</script>
</body>

You're close. Include jQuery in <head>:
<script src="//code.jquery.com/jquery-latest.js"></script>
Then in your JS:
<script type="text/javascript">
var colorsMap = {
'cl_option1' : "red",
'cl_option2' : "blue",
'cl_option3' : "yellow",
'cl_option4' : "black"
};
$('#colors').change(function(){
$("#salute").css('color', colorsMap[$(this).val()]);
});
</script>
The original script is too clumsy & mixing up non-jQuery & jQuery functions.

The biggest issue I see, besides your lack of jQuery being included in the page, is your js is being executed right away. Both of your attempts use js to talk to the DOM where those html nodes are, however, the DOM my not be ready with those nodes when your scripts are running.
jQuery offers a way to do this with a single line, if you prefer to go that route. If you want to learn native js, which I highly recommend, you'll want to read up on listening for when the window is ready.

To answer your questions:
The first code block (non-jQuery) was using selectedIndex for your select element, which was returning a numerical value (the index value) of the selected item. You wanted the string value to check against your map of colors. Updating your code so it looks something like:
var colors = document.getElementById('colors');
colors.onchange=function(){
var salute = document.getElementById("salute");
var item = document.getElementById("colors").value;
var color = colorsMap[item];
salute.style.color = color;
}
will work.
Updated fiddle: http://jsfiddle.net/pH4wW/2/
The second one, you just need jQuery :)

There are so many thing has to be changed in the code.
If you are doing it with js
colors.onchange=function(){
var salute = document.getElementById("salute");
var item = document.getElementById("colors").selectedIndex;
var color = colorsMap[item];
salute.style.color = color;
};
has to be changed to
document.getElementById("colors").onchange=function(){
var salute = document.getElementById("salute");
var item = document.getElementById("colors").value;
var color = colorsMap[item];
document.getElementById("salute").style.color = color;
};
you have to attach onchange event using document.getElementById
if jquery
$('#colors').change(function(){
var salute = document.getElementById("salute");
item=$(this).val();
cl = colorsMap[item];
$('#salute').css('color', cl);
});
Also you are missing jquery library.

Related

How to make a html page pick a random title on load?

I'm new to web development and can't seem to find this specific task anywhere on this site, only things related to dynamic changes while using a page. Basically, I want the contents of the tag in my part of my html document to always be different when loading/refreshing the page; I want to store some kind of array of strings in JS, and have the page, upon loading the html, pick one of these strings to insert into the tag.
This will result in every time I refresh the page, the title on the tab is different, and will not change unless I refresh again.
Can anyone point me to how I might do this? Completely stuck, and out of ideas after my window.onload didn't work.
EDIT: I have tried this code based on what I found on this site, but the title didn't change; and I'm not sure why.
var titles = ['rainy skies == best', 'now with more bugs!', 'c > java'];
window.onload = function() {
document.title = titles[(Math.random() * 10) % 2];
$('meta[name="description"]').attr("content", 'My website!');
};
(This is then linked into the html page as per usual)
You can add a little piece of Javascript. It will be executed each time the page loads and can change the page title dynamically.
<script>
var titles = ['asdf', 'qwer', 'uiop']
var title = titles[Math.floor(Math.random() * titles.length)] // pick random item
document.title = title
</script>
The usage of a backend language like PHP can solve the issue too, but this is much simpler.
Server-side example. Define a list of titles, pick a random one, and output it in the title attribute.
Get random item from array
PHP
<?php
$titles = ['title1', 'title2', 'title3'];
?>
<html lang="">
<head>
<title><?php echo $titles[array_rand($titles)]; ?></title>
</head>
...
</html>
You should use document.title to change the title in the tab of the website.
const strings = ["bar", "foo", "banana", "apple", "orange", "red", "green", "blue", "brown", "gray"];
window.onload = () => {
let random = Math.floor(Math.random() * strings.length);
// example with a div
document.getElementById("my-span").innerHTML = strings[random];
// example with page title
// document.title = strings[random];
};
<span id="my-span"></span>
HTML:
<head>
<title id="title"></title>
</head>
Javascript:
window.onload = function() {
var titles = ['rainy skies == best', 'now with more bugs!', 'c > java'];
var random = Math.floor(Math.random() * titles.length);
var titleElement = document.getElementById('title')
titleElement.innerHTML = titles[random];
}
EDIT: innerHTML instead of html

Trouble Getting HTML Input Into JS

So, I'm trying to build a decimal to binary converter for my computer science class. I already made an algorithm in Python that seems to be working pretty well. It works in the Javascript console perfectly fine too. I'm now at a point trying to accept input from an HTML form. I'm kind of a DOM noob, but I thought this would be something easy and fun to do, but it's turning out that it's a lot more confusing than I thought. I would know how to do this in React.js, but I'm trying to use this as a learning experience. Basically, I want to take input from a form, run it through a function and have the returned value of the function back into HTML. I know how to get the value into HTML, but I have no clue how to retrieve the form data into Javascript. Here's a Codepen with my progress so far.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Binary Calculator</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<center><form style="margin-top: 25%" id="myForm">
<input type="text" class="form-control" style="width: 250px" placeholder="Type a number!" id="textForm">
<br />
<input type="button" class="btn" style="margin-top: 15px" value="Submit">
</form></center>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
Javascript:
function conversion(){
var quotient = 15;
var convertedNum = [];
if (formValue == 0){
convertedNum = [0]
}
while(formValue >= 1){
quotient = formValue/2;
var mod = formValue %2;
formValue = quotient;
convertedNum.push(mod);
convertedNum.reverse();
}
console.log(convertedNum.join(""));
}
$('#textForm').change(function(){
var formValue = document.getElementById('#textForm').value;
parseInt(formValue);
console.log(formValue);
console.log("It's Working in Console!");
conversion();
});
Her's a simple way doing what you are trying to accomplish.
function myFunction() {
var x = document.getElementById("myText").value;
document.getElementById("demo").innerHTML = x;
}
</script>
<body>
First Name: <input type="text" id="myText" >
<p>Click the button to display the value of the value attribute of the text field.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
You want to put the answer back onto the page to be displayed when they click submit?
First you'll need a container (well, you can create one on the fly in Javascript, but typically you would just create an empty div container to hold the answer).
Add a div container for the solution: (after form probably)
<div id="convertedToBinary" class="answerDiv"></div>
It looks like you're using jQuery, which makes entering HTML into a target easy.
Add this to your conversion function:
$('#convertedToBinary').html(formValue+" converted to binary is: "+convertedNum.join("") );
<head>
<title></title>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
</head>
<body>
<input type="text" class="form-control" />
<span id="result"></span>
<script>
var formValue;
function conversion()
{
var quotient = 15;
var convertedNum = [];
if (formValue == 0)
{
convertedNum = [0]
}
while (formValue >= 1)
{
quotient = parseInt(formValue / 2);
var mod = formValue % 2;
formValue = quotient;
convertedNum.push(mod);
convertedNum.reverse();
}
$('#result').html(convertedNum.join(""));
}
$('.form-control').keydown(function ()
{
var $this = $(this);
setTimeout(function ()
{
formValue = $this.val();
conversion();
}, 100);
});
</script>
</body>
</html>
Just a couple of hints starting from the HTML / JS you provided:
You are using a jQuery selector within plain JS, so this won't work:
var formValue = document.getElementById('#textForm').value;
Change that to
var formValue = document.getElementById('textForm').value;
if you want to use plain JavaScript - or do it the jQuery way, like so
var formValue = $('#textForm').value;
You could also have stored the reference to that DOM element in a var, up front, and then work on that, but that's another topic.
Also you must pass the formValue to the conversion function, like so
conversion(formValue);
otherwise you can't work with the input value within the function scope.
All that remains to do is writing the resulting value into the innerHTML of some . The other answers give you two options for doing that - in jQuery (innerHTML) or plain old JavaScript.

Include javascript and html code from another file

I have a project that consists of multiple visualizations, all using the same dropdown menu for selecting what csv to load. I want to be able to add new options once and have it changed on all the files. Best way is to use html and javascript code in one file, and have it included on the others, so that if I want to add more options in the dropdown menu I only do it in that single file. Is there a way to do this with html, and if so, do I have to change the layout of the reusable "A" file so that it is properly used inside the rest? If it cannot happen with html, what is the best way to do it and what changes to I have to make in the code layout in the documents?Here is the reusable code that has to be on file A:
<div id="dropdown">
<select id = "opts">
<option value = "ds1">Atlas</option>
<option value = "ds2">BioSQL</option>
<option value = "ds3">Coppermine</option>
<option value = "ds4">Ensembl</option>
<option value = "ds5">Mediawiki</option>
<option value = "ds6">Opencart</option>
<option value = "ds7">PhpBB</option>
<option value = "ds8">Typo3</option>
</select>
</div>
<script type="text/javascript">
var ds1="../CSV/atlas/results/metrics.csv";
var ds2="../CSV/biosql/results/metrics.csv";
var ds3="../CSV/coppermine/results/metrics.csv";
var ds4="../CSV/ensembl/results/metrics.csv";
var ds5="../CSV/mediawiki/results/metrics.csv";
var ds6="../CSV/opencart/results/metrics.csv";
var ds7="../CSV/phpbb/results/metrics.csv";
var ds8="../CSV/typo3/results/metrics.csv";
</script>
And I want to include this after the style block in files B,C,D etc that look like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>D3 Test</title>
<script type="text/javascript" src="../d3/d3.js"></script>
<script type="text/javascript" src="../d3/d3-tip.js"></script>
<style type="text/css">
body{
font: 16px Calibri;
}
</style>
<!--...HERE IS WHERE I WANT TO INSERT THE CODE FROM THE A FILE-->
</head>
<body>
<script type="text/javascript">
I have seen other posts asking somewhat the same thing, but haven't found a way to do this. I think it has to do mostly with the fact that I insert both html and javascript code, but I'm generally new to this and cannot figure the proper way. Thanks in advance for any help.
Let's assume you store what you call file A in options.html, then my suggestion is the following:
"script.js":
// because you put your script in the <head> of B,C,D we wait for the page to load
window.onload = function () {
// We locate the dropdown menu
var dropdownMenu = document.getElementById('dropdown');
// load the file via XHR
loadHTML(function (response) {
// the response will be a string so we parse it into a DOM node
var parser = new DOMParser()
var doc = parser.parseFromString(response, "text/html");
dropdownMenu.innerHTML = doc.getElementById('dropdown').innerHTML;
// in case you want to do something with the references to the .csv files
var csvFiles = doc.getElementsByTagName('script')[0];
console.log(csvFiles);
})
};
function loadHTML(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("text/html");
xobj.open('GET', 'options.html', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
Note that this only runs, if you host it on a http-Server. In other words it won't run locally due to Same-origin policy.
Parsing string to DOM was inspired by this answer.
loading the HTML file via XHR was inspired by this post on codepen.
I modified your version of B,C,D:
reference to script.js in the head-Element
added a div-Element with ID "dropdown"
That's done with php just call it like this:
<?php include('file.html'); ?>

Better way to apply javascript scripts

Hello SO I'm relatively new to html and javascript and I currently want to make a page that will fulfill certain operations such as finding the max number of an array of numbers and factorial of a number as shown below.
and here is how I am organizing these sections
<!DOCTYPE html>
<html lang = "en">
<head>
<title>HTML/CSS Responsive Theme</title>
<meta charset = "utf-8">
<link rel = "stylesheet" href = "main.css" type = "text/css">
<meta name = "viewport" content = "width=device-width, initial-scale=1.0">
<script>
function startFactorial(number)
{
function factorial(num)
{
if(num <= 1)
return 1;
return num * factorial(num - 1);
}
document.factorials.factorialsfield.value = factorial(number);
}
function startMaxofFive(str)
{
//can actually find the max of n numbers not limited to 5
function maxoffive(string)
{
var nums = (string.match(/[-]?\d+/g));
var b = nums.map(Number);
return Math.max.apply(Math,b);
}
document.mof.moffield.value = (maxoffive(str));
}
</script>
</head>
<body>
<section id = "first">
<h3>Factorial</h3>
<form name= "factorials">
Enter a number <input type = "number" name = "factorialsfield" value = 0>
<br><br>
<input type = "button" onClick = "startFactorial(factorialsfield.value)" value = "Calculate"/>
</form>
</section>
<br>
<section id = "second">
<h3>Max of Five Numbers</h3>
<form name = "mof">
Enter 5 numbers <input type = "text" name = "moffield" placeholder = " separate each number by commas" size = 26>
<br><br>
<input type = "button" onClick = startMaxofFive(moffield.value) value = "Calculate"/>
</form>
</section>
<br>
<section id = "third">
<h3>Sum and Multiply</h3>
<form name = "operations">
Enter numbers to apply operations <input type = "text" name = "operationsfield"
</form>
</section>
</body>
</html>
What I wanted to ask you all is is there a better way to access those functions in my script without having to create another function just to use them?
Here's some suggestions:
You can use document.getElementById( id ) to get specific elements where id is the HTML's element id <element id="id_name">.
Events allow you to trigger actions based on user input. It works basically the same, but you no longer need to name the functions: element_variable.event = function() { /* ... */ }
See if the inner functions are really neccessary; see if you can edit the code where you no longer need that function (document.getElementById will probably be able to let you do that stuff)
Example:
<form id="factorials" name="factorials">
<!-- Skipping input -->
<input type="submit" <!-- ... -> />
</form>
// Javascript file
var fact = document.getElementById( "factorials" );
fact.onsubmit = function() {
/* Your code here */
}
It's generally considered best practice to move scripts to the bottom of the page before the closing body tag. This way the loading of the scripts won't interfere with page load.
You can also move your scripts to a separate file and include it:
<script src="myscripts.js"></script>
This will help keep your code more neat and organized.
You always use functions to call functions. Sounds weird but thats how it is :P
You can remove the JS calls from your DOM by adding eventlisteners to your JavaScript file just like this example:
<script>
var x = document.getElementById('test');
x.addEventListener('click', function(){
// your function magic happens here
});
</script>
<div id="test"></div>
Sorry if I understood your question wrong
I am not sure that this is what you asked for, however, it seemed like you wanted to know about other methods to get access to your javascript code or script in your HTML.
I can truly recommend you, to look into Angular for this. With Angular you can call methods in your controller, and scope data between your view (HTML) and controller (Javascript).
https://angularjs.org/
But this is just one of many options!

Accessing inline CSS properties using getElementsByClassName

I have this piece of HTML code.
<div class="tagWrapper">
<i style="background-image: url(https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/390945_10150419199065735_543370734_8636909_2105028019_a.jpg);"></i>
</div>
I need to get that url within the brackets. I tried using the getElementsByClassName() method but it didn't work. Since url is not a HTML element, I have no idea on how to take out the value. I can't use getElementById(), because I can't add an id to the HTML (it's not mine). It needs to work in Chrome and Firefox. Any suggestions?
You didn't add a jQuery tag, so here's a native solution (note that this likely won't work on older versions of IE, but you said it only has to work on Chrome and FF):
var origUrl = document.getElementsByClassName("tagWrapper")[0]
.children[0].style.backgroundImage;
var url = origUrl.substr(4, origUrl.length - 5);
Or
var url = origUrl.replace("url(", "").replace(")", "");
Here's a fiddle
EDIT
Answering your comment
document.getElementsByClassName("tagWrapper")
gets all elements with the class name tagWrapper. So to get the first one, you grab the zero index
document.getElementsByClassName("tagWrapper")[0]
Then you want the first child under there, and the backgroundImage property on this first child.
document.getElementsByClassName("tagWrapper")[0]
.children[0].style.backgroundImage;
From there it's a simple matter stripping the url( and ) from it
var url = origUrl.substr(4, origUrl.length - 5);
or
var url = origUrl.replace("url(", "").replace(")", "");
You can use querySelector():
Demo: http://jsfiddle.net/ThinkingStiff/gFy6R/
Script:
var url = document.querySelector( '.tagWrapper i' ).style.backgroundImage;
url = url.substr(4, url.length - 5);
If you where using jquery you could do something like this
$(".tagWrapper i").css("background-image")
I think if you use jQuery it will be easer.
var w = document.getElementsByClassName('tagWrapper')[0];
for (var i=0; i<w.childNodes.length; i++)
if (w.childNodes[i].tagName && w.childNodes[i].tagName.toLowerCase() == 'i')
return w.childNodes[i].style.backgroundImage;
<div class="tagWrapper">
<i id="something" style="background-image: url(https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/390945_10150419199065735_543370734_8636909_2105028019_a.jpg);"></i>
</div>
// script / without jQuery
var url = document.getElementById('something').style.backgroundImage.match(/\((.*?)\)/)[1];
Use jQuery!!!
$("div.tagWrapper i").css("background-image").substr(4, $("div.tagWrapper i").css("background-image").length-5)
Example
If You don't have to care about Microsoft browsers, the raw JavaScript is quite easy. You can use getElementsByClassName and getElementsByTagName, however it is easier to try querySelectorAll. I've included both. The use of regular expression preserve relative links.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type='text/javascript'>
var do_find_a = function() {
var tmp = document.getElementsByClassName('tagWrapper')[0];
var tst = tmp.getElementsByTagName('i')[0].getAttribute('style');
return do_alert(tst);
}
var do_find_b = function() {
var tst = document.querySelectorAll('.tagWrapper i')[0].getAttribute('style');
return do_alert(tst);
}
var do_alert = function(tst) {
var reg = /background-image:\s*url\(["']?([^'"]*)["']?\);?/
var ret = reg.exec(tst);
alert (ret[1]);
return;
}
document.addEventListener('DOMContentLoaded',do_find_a,false);
document.addEventListener('DOMContentLoaded',do_find_b,false);
</script>
</head>
<body>
<div class='tagWrapper'>
<i style='background-image: url("http://example.com/image.jpg");'></i>
</div>
Text to ignore.
</body>
</html>
And jsFiddle version:
http://jsfiddle.net/hpgmr/

Categories

Resources