I am learning javascript and I have a problem with changeimage function.
I need to change both one, and second image.
Here is jsfiddle.
https://jsfiddle.net/7ewjoxnv/1/
And here below, javascript:
var switchingImage;
function changeImage()
{
switchingImage.src = this.value;
}
window.onload = function() {
var radios = document.getElementById('imageSwitcher').getElementsByTagName('input');
switchingImage = document.getElementById('imageToSwitch');
for(var i=0;i<radios.length;i++)
{
radios[i].onclick = changeImage;
}
var radios = document.getElementById('imageSwitcher2').getElementsByTagName('input');
switchingImage = document.getElementById('imageToSwitch2');
for(var o=0;o<radios.length;o++)
{
radios[o].onclick = changeImage;
}
}
Any help will be much appreciated.
Best Regards,
David!
When you do var radio = and switchingImage = for the second time, you are changing their previous values.
In the case of radios it just happens and does not affect you because you have already applied the listeners you wanted to the old radio buttons.
In the case of switchingImage however, it affects you, because switchingImage will ultimately point to the document.getElementById('imageToSwitch2'). So when you call changeImage() it will always operate on document.getElementById('imageToSwitch2').
Here's one way you could solve your problem. It is purposefully not the best solution. Use it as a baseline to improve on it.
https://jsfiddle.net/7ewjoxnv/4/
Related
I have created a button using javascript and now I want to give it a onclick. however I want the function to have a parameter i. the problem is that when I inspect the console the onclick function is just onclick=playAudio(i). I want it to be different for each value of i in the for loop, but because it is in brackets it just stays as i instead of the current number in the for loop. I hope I have explained this properly. some of the code is below to help you understand.
var i;
var audioMp3 = ["audio/Un", "audio/Deux", "audio/Trois", "audio/Quatre", "audio/Cinq", "audio/Six", "audio/Sept", "audio/Huit", "audio/Neuf", "audio/Dix"];
for(i = 0; i < audioMp3.length; i++{
var audioBtn = document.createElement("BUTTON");
audioBtn.setAttribute("onclick", "playAudio(i);";
}
var audioMp3 = ["audio/Un", "audio/Deux", "audio/Trois", "audio/Quatre", "audio/Cinq", "audio/Six", "audio/Sept", "audio/Huit", "audio/Neuf", "audio/Dix"];
for(var i = 0; i < audioMp3.length; i++){
var node = document.createElement("BUTTON");
var textnode = document.createTextNode(audioMp3[i]);
node.appendChild(textnode);
node.setAttribute("onclick", "playAudio("+i+");");
document.getElementById("element").appendChild(node);
}
function playAudio(i){
alert(i);
}
<div id="element"></div>
I'm pretty sure that this should work :
audioBtn.setAttribute("onclick", "playAudio("+i+");");
audioBtn.onclick = function(){
playAudio(i)
}
Create an array with all the possible values, loop through the values to create the buttons, each button should have their click event listener to play their own button's song.
I don't know your precise code but that is the pseudo-code to do it.
I just started learning JavaScript.
I'm trying to change the text on a click.What's wrong with this code.
Please let me know.
Thanks
<!DOCTYPE html>
<html>
<body>
<script>
function change_text(id)
{
var arr = new Array("Now Click Again",""oops! Once more!","I'm Leaving!","Good Bye!");
var x = Document.getElementById("heading");
for(var i=0;i<arr.length;i++)
x.innerHTML=arr[i];
x.style.visibility="hidden";
}
</script>
<h1 onclick="change_text()" id="heading">Click on this text!</h1>
</body>
</html>
For one thing, you have two quotes here:
""oops! Once more!"
should be:
"oops! Once more!"
Document needs to be all lower-case (document).
change_text(id) is never used, and
x.style.visibility="hidden" needs to be moved outside the for loop.
You don't need a for loop at all, though, you just need to increment i++ every time the method is called, otherwise it will skip straight to "Goodbye".
<script>
var i = 0;
function change_text()
{
var arr = new Array("Now Click Again","oops! Once more!","I'm Leaving!","Good Bye!");
var x = document.getElementById("heading");
i++;
x.innerHTML=arr[i];
if(i >= arr.length) {
x.style.visibility="hidden";
}
}
</script>
EDIT:
EDIT2: OK, you got the idea before!
instead of "heading"
var x = Document.getElementById("heading");
you need to put the passed in value, id.
var x = Document.getElementById(id);
before this, you never actually use that id.
Also remember to pass that id in,
h1 onclick="change_text('heading')"
Change this line;
var arr = new Array("Now Click Again",""oops! Once more!","I'm Leaving!","Good Bye!");
and this line
var x = Document.getElementById("heading");
to this;
var arr = new Array('Now Click Again','oops! Once more!','I\'m Leaving!','Good Bye!');
var x = document.getElementById(id);
First, i don't know if it is a typo in your question but you have one extra " in your string array, this is how it should look.
var arr = new Array("Now Click Again","oops! Once more!","I'm Leaving!","Good Bye!");
And I don't know what you are trying to do with your for loop but the text you are showing will always be the last one in your array. Could you clarify what your are trying to achieve with the text in the h1 element?
Last of all, if you hide your element clearly your text won't show up, you should remove this line unless there is something I didn't understand correctly :
x.style.visibility="hidden";
Oh, and I think that your script element should have a type="text/javascript"
<script type="text/javascript">...
Unrelated to the question but if you can't spot the strings mistake in your array maybe you should change IDE. Even Notepad++ colors the strings, it might have helped you figure this one out.
Bonjour ! here is my question, I'm using, two "kinds" of JS short functions (5 lines of code per function) but I have to make, let's say, about 10 of each kind. It would be a total of 100 lines of code which is very long... So I was wondering if there could be an easy and very shorter way to implement this. I know very very few in javascript and I like roughly understand what I write. (If possible, avoid using JQ, for which I absolutely don't understand a word !)
Here are the functions :
function typedepolice() {
var nodes = document.getElementById('stripid').childNodes;
var nompolice = document.Selections.police.options[document.Selections.police.selectedIndex].value;
for(var i=0; i<nodes.length; i++) {
if (nodes[i].nodeName.toLowerCase() == 'div') {
nodes[i].style.fontFamily = document.Selections.police.options[document.Selections.police.selectedIndex].value;
}
}
}
html calling : ...<select name="police" id="police" size="1" onchange="typedepolice()">...
function colbandeau() {
var nodes = document.getElementById('stripid').childNodes;
var colorFmsg = document.getElementById("colorFmsg").value;
for(var i=0; i<nodes.length; i++) {
if (nodes[i].nodeName.toLowerCase() == 'div') {
nodes[i].style.background = '#' + document.getElementById("colorFmsg").value;
}
}
}
html calling : ...<input id="colorFmsg" class="color3" value="FFFFFF" size="5" onchange="colbandeau()">...
The first one refers to a selected option of a dropdown selection box.
The second one to a color selected with JSColor which is a JS plugin to choose a color.
As you see, they are intended to dynamically change CSS properties of numerous div children of one element which Id is "stripid", and are called by "onchange" events.
After a long search, I found the pattern of these functions in a reply in stackoverflow and they are exactly what I needed. For this, I thank very largely Vijay Agrawal, because it will improve a lot my web page.
NB : don't be afraid, "police" is meaning "font" in French :)
If someone could help me, it would be great !
You can create a function to set the stripid child nodes
function setNodeStyle(value, style) {
var nodes = document.getElementById('stripid').childNodes;
for (var i=0; i<nodes.length; i++) {
if (nodes[i].nodeName.toLowerCase() == 'div') {
nodes[i].style[style] = value;
}
}
}
Then you can call it in the other functions:
function colbandeau() {
setNodeStyle(document.getElementById("colorFmsg").value, "background");
}
This will already save you quite a bit.
You can improve on this even more by setting an attribute that contains the value that is to be. To get you started:
<input class="color3 changer" value="FFFFFF" size="5" data-style="background">
Array.prototype.forEach.call(document.querySelector(".changer"), function (el) {
el.addEventListener("change", function () {
setNodeStyles(this.value, this.dataset.style);
});
});
I hope it's not a problem to post much specific code here, but I figure it will be better explained if everyone can just see it, so I will give you my code and then I will explain my problem.
My code:
function addBeGoneLinks () {
var beGoneClassElems;
var beGoneSpan;
var beGoneLink;
var beGonePrintSafe;
var spacesSpan;
//var middotSpan = document.createElement ('span');
var interactionContainer = document.getElementsByClassName('feedItemInteractionContainer');
for (var i=0; i<children.length; i++)
{
beGonePrintSafe = false;
beGoneClassElems = children[i].getElementsByClassName('beGone')
beGonePrintSafe = true;
if (beGoneClassElems.length == 0)
{
beGoneLink = document.createElement('a');
beGoneLink.href = 'javascript:void(0);';
beGoneLink.appendChild(document.createTextNode('Be Gone'));
beGoneLink.className = 'beGone';
beGoneLink.id = 'beGoneLink' + i.toString();
beGoneLink.addEventListener ("click", function() {beGone();}, false);//This line!
beGoneLink.align = 'right';
spacesSpan = document.createElement('span');
spacesSpan.innerHTML = ' - ';
if (interactionContainer[i] != undefined)
{
interactionContainer[i].appendChild(spacesSpan);
interactionContainer[i].appendChild(beGoneLink);
}
}
}
}
Here I have a function from a Greasemonkey script that I am working on. When one of the links is clicked, my aim is to have it call the function beGone() which will, among other things, remove the whole element a few parents up, thereby removing their sibling's, their parents and their parents' siblings, and one or two levels after that.
My idea was just to get the id of the link that was pressed and pass it to beGone() so that I could then get the parents using its id, but I do not know how to do that. Am I able to have the id of a link passed by the function that it calls? If not, is there any other way to do this?
I am not sure whether I am missing some really simple solution, but I haven't been able to find one rooting around the web, especially because I was unsure how I would search for this specific problem.
Try this:
beGoneLink.addEventListener("click", beGone, false);
beGone = function (evt) {
evt.target; // evt.target refers to the clicked element.
...
}
You can then use evt.target.id, evt.target.parentNode, etc.
I have been able to successfully get another elements onclick function by doing this:
document.getElementById(this.options[this.selectedIndex].text).getAttribute('onclick')
This gives me the exact text that I want to put into a different elements onchange event, so I thought I could do this:
<select onchange="document.getElementById(this.options[this.selectedIndex].text).getAttribute('onclick')">
This does not work though. Does anyone have any ideas, I am stumped?
You can't just dump a function into an attribute like that. I recommend that you start writing unobtrusive JavaScript.
HTML
<select id="mySelect">
<!-- snip -->
</select>
JavaScript
var select = document.getElementById('mySelect');
select.onchange = function () {
var id = this.options[this.selectedIndex].text,
clickHandler = document.getElementById(id).onclick;
clickHandler.apply(this);
};
Demo →
Edit re: OP's comment
"Is there an easy way to apply this to all the selects on the page?"
Of course there is! But you need to be careful about not creating functions in a loop (it won't work).
var selects = document.getElementsByTagName('select'),
numSelects = selects.length,
i;
function setClickHandler(element) {
element.onchange = function () {
var id = this.options[this.selectedIndex].text,
clickHandler = document.getElementById(id).onclick;
clickHandler.apply(this);
}
}
for (i=0; i<numSelects; i++) {
setClickHandler(selects[i]);
}
I haven't tested this, but perhaps:
var handler = document.getElementById(this.options[this.selectedIndex].text).getAttribute('onclick');
var selectEl = document.getElementsByTagName('select')[indexOfSelect];
selectEl.setAttribute('onClick',handler);
The following works (more or less the same as above, except using the 'onFocus' attribute on the select element):
var handler = document.getElementById('first').getAttribute('onclick');
var selectEl = document.getElementsByTagName('select')[0];
selectEl.setAttribute('onfocus',handler);
JS Fiddle demo
This is not recommended but the simplest fix that would work,
<select onchange="function() {document.getElementById(this.options[this.selectedIndex].text).getAttribute('onclick')();}">