This question already has answers here:
How can I change an element's class with JavaScript?
(33 answers)
Closed 6 years ago.
I'm trying to program a button that randomly picks a color from the color array and chooses between these four values, and the color will be given to a new element.
They're classes that are defined in css. It's not working properly though as I don't see the issue with what I'm doing.
<script>
var colorArray = [ '.st1', '.st2', '.st3', '.st4'];
var randomColor = Math.floor(Math.random()*colorArray.length);
</script>
<label>
Class: <input type="text" id="new-class" value="randomColor">
</label>
<button type="button" onclick="addObject()">
Make Ball
</button>
Can anyone see to what I'm doing wrong?
To use a javascript variable as an HTML value, you have to set it in javascript. So to set your value attribute, do it like this:
And you need to wrap the code in the function that you set in the onClick
<script>
function addObject(){
var colorArray = ['.st1', '.st2', '.st3', '.st4'];
var randomColor = Math.floor(Math.random() * colorArray.length);
console.log(colorArray[randomColor]);
document.getElementById("new-class").className = colorArray[randomColor];
}
</script>
Related
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 2 years ago.
I am trying to make a website, in which one makes a questions and there will be options for that questions.
I have a add option button, when user clicks the add option button, new option is added by this function.
function addOption(elem) {
elem = $(elem);
let ul = $(elem.parent().children()[1]);
let addedElem = $(
`<li class='ques-li'><input type='text' name='ques-option' class='ques-option' value='Option'><p class='remove-op'>X</p></li>`
);
addedElem.appendTo(ul);
}
let addOp = $('.ques-add');
$('.ques-add').click(function () {
addOption($(this));
});
This works well with one question, but when a user adds another question.
It is by this function.
let addQuestion = $('form button');
addQuestion.click(function () {
let quesBox = $('div.questions-box');
quesBox.html(quesBox.html() + `<div class='ques'>
<input type="text" name="ques-name" class="ques-name">
<ol class='ques-ul'>
<li class='ques-li'><input type="text" name='ques-option' class='ques-option'>
<p class='remove-op'>X</p>
</li>
<li class='ques-li'><input type="text" name='ques-option' class='ques-option'>
<p class='remove-op'>X</p>
</li>
</ol>
<p class='ques-add'>Add Another</p>
</div>`)
});
When i click the add Question button, it also works
but when i click the add option button on a newly created question,
it does not create a new option.
I noticed when i create a new question, it does not get the new option button.
So, i updated my code as follows :-
let addOp = $('.ques-add');
$(document).bind('DOMNodeInserted', function(){
addOp = $('.ques-add');
});
addOp.click(function () {
addOption($(this));
});
It also does not work.
I have no idea why this code is not working.
Thanks in advance.
Try using delegation approach that uses .on(). This will assure that the event will be attached to all the elements that are added to the document at a later time:
$('body').on('click', '.ques-add', function () {
addOption($(this));
});
I cannot update the value for userPickColor for some reason, it is always undefined. But I try to console.log inside the functions and my values are actually changing. But for some reasons, once I call it outside the function, it doesn't update at all.
I'm still new to Javascript so Please Help me
Here is my code:
var white = document.getElementById("white");
var black = document.getElementById("black");
var userPickColor;
white.addEventListener("click", whiteshirt);
black.addEventListener("click", blackshirt);
function whiteshirt(){
userPickColor= "white";
}
function blackshirt(){
userPickColor= "black";
}
ShirtDescrp.innerHTML = userPickColor;
As others have said, you need to place the line that updates the .innerHTML inside of the callback functions so that after the variable has been updated, you can update the page with the most current variable value as well.
But, taking this one step further... There is a common coding methodology called DRY (Don't Repeat Yourself) and you've got two callback functions that largely do the same thing. The only difference is the actual text that gets set. Those two functions run when one of two elements on your page get clicked and those two elements have the text you want to use as their ids. We could easily combine the two callbacks into just one like this:
var ShirtDescrp = document.getElementById("des");
// There's nothing wrong with variables if they help you read the code
// more easily, but if you won't be using the value they store more than
// once, they don't really add much.
document.getElementById("white").addEventListener("click", changeColor);
document.getElementById("black").addEventListener("click", changeColor);
function changeColor() {
// No variable needed. Just set the text to the id of the element that got clicked
// "this" here refers to the object that initiated the call for the current function
// which will be one of the two buttons.
ShirtDescrp.innerHTML = this.id;
}
<button id="white">white</button>
<button id="black">black</button>
<p id="des"></p>
you have to put ShirtDescrp.innerHTML = userPickColor; inside your event listener as well since you change the variable but you didn't tell the dom to update the content
You should update the DOM same as the variable:
var white = document.getElementById("white");
var black = document.getElementById("black");
var ShirtDescrp = document.getElementById("des");
var userPickColor = null;
white.addEventListener("click", whiteshirt);
black.addEventListener("click", blackshirt);
function whiteshirt() {
userPickColor = "white";
ShirtDescrp.innerHTML = userPickColor;
}
function blackshirt() {
userPickColor = "black";
ShirtDescrp.innerHTML = userPickColor;
}
<button id="white">white</button>
<button id="black">black</button>
<p id="des"></p>
You have already got your answer... Change doesn't affect as update is not happening inside event listener. This is just a recommendation how I would do it (especially if i had more color options):
<p id="color-name">none</p>
<div class="color-buttons">
<button id="white">White</button>
<button id="black">Black</button>
<button id="orange">Orange</button>
<button id="blue">Blue</button>
<button id="green">Green</button>
<button id="red">Red</button>
</div>
JavaScript like:
var buttons = document.querySelectorAll(".color-buttons button");
var color_name = document.getElementById("color-name");
buttons.forEach(function(btn){
btn.addEventListener("click", function(){
color_name.style.background=this.id;
color_name.innerHTML=this.id;
});
});
Here is the fiddle to play around.
I would also probably generate those buttons dynamically as well. And also wouldn't use id to store color but i would use something else like data-color='red' for example.
This question already has answers here:
Why isn't my JavaScript working in JSFiddle?
(7 answers)
Closed 5 years ago.
I am making an idle game and want something to be purchased on user click. I have an onclick event connected to it which triggers the buyCreateScript() function but it is not working. Any advice?
Fiddle:https://jsfiddle.net/wizviper/m1ftgoyp/82/
Javascript:
function buyCreateScript() {
if(bytes >= createScriptCost ) {
createScriptAmount++;
bytes = bytes - createScriptCost;
createScriptCost = createScriptCost * priceIncrease;
}
}
HTML:
<button type="button" class="btn-primary" id="createScript"
onclick="buyCreateScript()">Create Script-0</button>
You need to change how you load the javascript in your fiddle.
Click on the javascript options cog icon
Change "LOAD TYPE" to "No wrap - in < head>"
Click "Run" and try again
The solution is to either:
Keep the onclick attribute but add a script tag in the html section and write the function buyCreateScript() in it:
<button type="button" class="btn-primary" id="createScript" onclick="buyCreateScript()">Create Script-0</button>
<script>
function buyCreateScript() {
console.log('works');
}
</script>
Or, you could add an event listener in the javascript section, remove the onclick attribute and keep your function where it is:
var createScriptBtn = document.getElementById('createScript');
createScriptBtn.addEventListener('click', function() {
buyCreateScript();
});
function buyCreateScript() {
console.log('works');
}
<button type="button" class="btn-primary" id="createScript">Create Script-0</button>
This question already has answers here:
getElementByClassName Not Returning Results
(2 answers)
Closed 8 years ago.
I´m using the following code
<script type="text/javascript">
function getInfo() {
var myElement = document.getElementbyClassName("contentMiddle");
alert(myElement.ClassName)
}
</script>
When i´m clicking on the button now:
<input onclick="getInfo" type="button" value="ClickMe" />
In the body is the div class="contentMiddle"> with a table inside. But nothing is shown when i´m clicking on the button.
It should be getElementsByClassName not getElementByClassName. i.e. Get Elements not Element. Unlike id of an element classname does not have to be unique for the document. There could be many elements with the same class name and function returns all of them.
It returns an array of all the elements with that class name. If you need to access a certain element you need to use the index.
<script type="text/javascript">
function getInfo() {
var myElements = document.getElementsByClassName("contentMiddle");
if(myElements != null)
{
alert(myElements[0].className);
}
else
{
alert("No elements found !");
}
}
</script>
HTML:
<input onclick="getInfo()" type="button" value="ClickMe" />
I* have two <div> containers which needs to interchange their position of display on the change of a dropdown value.
So, how can this be achieved using Jquery?
bewlow are the two div containers who display position is needed to be interchanged
<div id="first"><p>I will be displayed on second place on dropdown's particular value</p></div>
<div id="second"><p>I will be displayed on first place on dropdown's same value for which first div is placed at second position</p></div>
Simple Using Javascript
<script>
function interchange()
{
var strDiv1Content = document.getElementById('first').innerHTML;
var strDiv2Content = document.getElementById('second').innerHTML;
document.getElementById('first').innerHTML = strDiv2Content;
document.getElementById('second').innerHTML = strDiv1Content;
}
</script>
using jQuery
<script>
function interchange()
{
var strDiv1Cont = $("#first").html();
var strDiv2Cont = $("#second").html();
$("#first").html(strDiv2Cont);
$("#second").html(strDiv1Cont);
}
</script>
Call function interchange on some button click like
<input type ='button' value ='interchange' onclick='interchange' />
This will do it.
var firstHtml = $('#first').html();
var secondHtml = $('#second').html();
$('#second').html(firstHtml);
$('#first').html(secondHtml);