JS Button - random font - javascript

<div id="fontfamily">test
</div>
<button onclick="myFunction()">Try it</button>
var fontType = [ "Arial", "Verdana", "Courier"];
var num;
num=Math.floor(Math.random()*3);
document.getElementById("fontfamily").style.fontFamily =fontType[num];
console.log(num);
function myFunction() {
var x = document.getElementById("fontfamily").name;
document.getElementById('myFunction()').innerHTML = x;
}
i dont know what not working. my goal is that in every time that i press the button the font change.
tnx!

There are many things wrong in your code, so let's review them one at a time.
First, onclick="myFunction()" runs myFunction when you click on the button, but it doesn't run the lines which aren't in the function. Your randomization code is before the function, so it is executed once, when the page loads.
Depending on where you put that code (such as in a script tag in the head), the page might not have loaded. This means the document.getElementById function will fail because the elements haven't loaded yet. That might be another reason why it's not working.
var x = document.getElementById("fontfamily").name;
document.getElementById('myFunction()').innerHTML = x;
This tries to get the name attribute of the div. There's no name attribute on that div, so it will fail. Next you're trying to get an element where the id is equal to myFunction(). That doesn't make any sense. myFunction() isn't an id on an element. I don't know what you were trying, so I just got rid of most of the useless code.
Here's the solution, simply done by moving the needed code inside the function.
var fontType = ["Arial", "Verdana", "Courier"];
function myFunction(e) {
document.getElementById("fontfamily").style.fontFamily = fontType[Math.floor(Math.random() * fontType.length)];
}
<div id="fontfamily">test</div>
<button onclick="myFunction(event)">Try it</button>

Related

Content of <script> printed instead of executed

Basically, I would like to know what could cause the content of a <script> tag to be printed instead of executed in HTML.
Context: I have accordion buttons, what I want to do is change the image in the button from a down arrow to an up arrow on click. I am using part of the code described here.
If i put my code in a fiddle, like this one (I replaced img with alts to avoid local files problems), it works.
However, in my code, if I put the script before the button, nothing happens, and if i put it after it, then the content of the script apears below the button when I click it (event if it's just var a = null, then it would print var a = null).
<button class="accordion" id="button_emotion">VIEWS<img id="button_emotion_img" src="images/arrow_grey.svg" width="30" height="30" alt="" style="float:right;margin:0 0px 0 0px;" /></button>
<script>
document.getElementById('button_emotion').onclick=function () {
document.getElementById('button_emotion_img').src = "images/arrow_grey_up.svg";
};
</script>
I have also tried using onClick="myFunction()" in the button tag with the same result.
What could be causing this?
UPDATE:
I have found the culprit. Later in the code, there is something like that:
<script>
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function(){
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("show");
}
}
</script>
I am not exactly sure what it does as I did not write this code, but it shows the next tags that are non "accordion" class. There is a modified bootstrap that makes it possible to print the content, however without it, it just doesn't execute the script, but does not print it either.
Here's the updated JSFiddle with the extra code. If you put the image changing part before the script or in a <script> in the HTML part, it doesn't execute it (and with the modified css would print it instead), but if you place it before, the code will execute.
Setting display CSS property of a <script> tag may result in its content being printed. That was the case for me.

Javascript function not being called, function may be dead?

I'm trying to call a js function when a button is clicked in html, but it won't run. The button is being clicked, because I tested a prompt and it showed up, but when we put a function there it wont run...
function NextLesson(){
prompt("myprompt");
document.getElementById("Kek23").innerHTML = <c:outvalue= "${lesson.GetNextLesson()}"/>";}
Then I call the method in a button
<p style="font-size: 4em" id ="Kek23"></p>
<button onclick = "NextLesson();" value = "Next"/>
We've found that when a function gives an error, javascript declares the entire function as dead, but I don't know the error
This works:
You had a couple syntax issues that was killing your function- including not completely wrapping your innerHTML content in quotes - and your Button element was not using the correct syntax.
<p style="font-size: 4em" id ="Kek23"></p>
<button onclick = "NextLesson();" value = "Next">Next</button>
<script>
function NextLesson(){
prompt("myprompt");
document.getElementById("Kek23").innerHTML = "<c:out value= ${lesson.GetNextLesson()}/>"
};
</script>
Fiddle
Errors corrected in the 2nd line of function:
function NextLesson(){
prompt("myprompt");
document.getElementById("Kek23").innerHTML = "<c:out value= '${lesson.GetNextLesson()}'/>";
}

Button onclick doesn't respond

I am fairly new to JavaScript and I am trying to make my own image gallery as my first simple project. I expected it to go smoothly, but it seems like I am doing some trivial mistake, and I have no idea where.
So, my initial plan was: I would set up an image element with empty src property, create an array of image names, add a function that will increase the array pointer by 1 any time it is triggered, and then just add the corresponding value in the array to the src.
It doesn't work, though. Could you please try to see any errors in the code? I really have no idea what to do, just can't find a mistake.
<html>
<body>
<img src="" id="imageCanvas">
<div id="counterDisplay"></div>
<script type="text/javascript">
var images = ["increased.jpg","knight.jpg","knight-g.jpg","golden.jpg","land.jpg"];
var counterDisplay = document.getElementById("counterDisplay");
var imageCanvas = document.getElementById("imageCanvas");
var imageCount = 0;
// function intended to increase the array position indicator by 1, but it always only increases it in relation to the original imageCount value (0), how to make it save the already increased value?
function changeCount() {
imageCount = imageCount+1;
}
counterDisplay.innerHTML = imageCount;
imageCanvas.setAttribute("src",images[imageCount]);
</script>
// The main problem: it just refuses to respond!
<button onclick="changeCount()">NEXT</button>
</body>
</html>
I didn't debug through this, but my guess is that onclick is being called, but you are not updating the count in that changeCount code.
Try putting almost all the code in changeCount.
function changeCount() {
imageCount = imageCount+1;
counterDisplay.innerHTML = imageCount;
imageCanvas.setAttribute("src",images[imageCount]);
}
This function runs when the the button is clicked.
function changeCount() {
imageCount = imageCount+1;
}
This code is run when the script first loads.
counterDisplay.innerHTML = imageCount;
imageCanvas.setAttribute("src",images[imageCount]);
You want it to run when the button is clicked. Move it inside the function.

JavaScript Change Text in X Seconds - No Initial Display

I currently have a JavaScript file that will change the testimonial shown every five seconds. Everything works perfectly, except for the first five seconds, nothing appears. If I put a value where the JavaScript function is being called, it does show up initially, then is replaced by whatever the first testimonial is.
Here is the HTML code where the JavaScript is being called.
<html>
<head>
<SCRIPT language="JavaScript" SRC="textCycle.js"></SCRIPT>
</head>
<body>
<table border = 0><tr><td style="width:300px;"> <!-- Change the height in order to determine width of quotes -->
<div id="change"></div></td></tr></table>
</body>
</html>
Here is the Javascript:
var quotes=new Array(5);
var i = 0;
var authors=new Array(5);
//Load Quotes into array
quotes[0]="\"Website is awesome!\"";
quotes[1]="\"Love it!\"";
quotes[2]="\"Awesome site!\"";
quotes[3]="\"This site was very informative and helped with my problem.\"";
quotes[4]="\"Best site for helping with this issue.\"";
//Load authors that correspond with the quote array
authors[0]="Anonymous";
authors[1]="Anonymous";
authors[2]="Anonymous";
authors[3]="Anonymous";
authors[4]="Anonymous";
//Call the changeText() function every 5000 miliseconds
setInterval(changeText, 5000);
//Function that determine what quote and author to put in html.
function changeText(){
document.getElementById("change").innerHTML=(quotes[i] + '<p style="text-align: right"><i>' + authors[i] + '</i></p>');
if(i == 4)
i = 0;
else
i++;
}
Is this just a matter of changing the javascript file so that quotes[0] is outside of the loop?
Note: The values in the arrays were changed to keep it anonymous. These aren't real testimonials.
Just add changeText() (call your function) anywhere in your code before setInterval(). Well, it is not mandatory.
Fiddle
If you add the call to changeText() as mentioned, it likely still will not work. This is because the DOM has not been parsed yet. You should call it after the DOM is ready. One way to do this would be to put it in the onload event. This is the easiest way without a third-party library, but also waits until all images have been loaded. Here is an example:
<body onload="changeText()">
setInterval waits the interval duration (5 seconds) before executing the first time.
You could just call it once before setting the interval, and you'll be good to go. Eg:
//Call the changeText() function every 5000 miliseconds
changeText();
setInterval(changeText, 5000);

change the position of div tag dyanmically with javascript

I have an ASP button in a div to the right side of a page. I want to change the position to the left in the same row dynamically with onchange event of a dropdown.
I did this way:
document.getElementById('divButtonGo').style.Paddingleft="80px"
How do I do this with Javascript?
The example you have provided already is javascript. If you want to change what triggers the code to run, change where you place it.
from an onchange event, into a function in a script tag that is called by something else.
example
<input type="button" onclick="movediv()" />
<script>
function movediv(){
document.getElementById('divButtonGo').style.Paddingleft="80px"
}
</script>
There's several things wrong here. In order of increasing importance:
You're missing the closing slash from your i tag.
I don't see a "divButtonGo" in your html. If it's not there at all, obviously it won't work. If it is, include it in your code snippet.
I'm pretty sure to set the style you're going to need elem.style.paddingLeft, not elem.style.Paddingleft
Your script isn't wrapped inside <script> tags. All Javascript has to be wrapped in these tags, and, in order for that code to operate sucessfully, it's going to have to be placed after the "divButtonGo", or you'll have to wire up an onload event, like window.onload = function() { /* Bombs away! */ };
Your final result should look something like...
<div id="divButtonGo">
My Awesome Content
</div>
<script type="text/javascript">
var el = document.getElementById("divButtonGo");
el.style.paddingLeft = "30px";
</script>
Also, to note, padding wont' exactly change the position of the div, only the position of the content inside. If you want to change the position of the div, use margin-left (in JS, element.style.marginLeft, i believe)
EDIT:
I forgot you wanted it in the onchange event of a dropdown; so you'd do somethign like:
var dropdown = document.getElementById("MyDropDown");
dropdown.onchange = function() {
var el = document.getElementById("divButtonGo");
el.style.paddingLeft = "30px";
};

Categories