im trying to make a switch wich will change two images. I once solved ths, but then i lost some important files, the one containing the final script being one.
The idea is that when the button is clicked, it will change image 1 for image 2 and will change its own image from on to off. Then, when clicked again it will change image 2 for image 1 and its own image from off to on.
I been trying something like this, buts not working, not sure why. I think i got the wrong declaration for the if which determines if the switch is on or off, but again not sure.
Before you read the code and realize its poorly done, consider i dont know a thing about javascript, i only have a vague idea of how it works.
<script type="text/javascript">
var vswitch = false;
if (document.getElementById("switchh").src = "http://www.sampleweb.com/on.gif") {
vswitch = true
}
else {
vswitch = false
}
function change(){
if (vswitch == true){
function changelamp() {
document.getElementById("lamp").src = "http://www.sampleweb.com/image2.png";
}
function changeSwitch() {
document.getElementById("switchh").src = "http://www.sampleweb.com/off.gif";
}
} else {
function changelamp() {
document.getElementById("lamp").src = "http://www.sampleweb.com/image1.gif";
}
function changeSwitch() {
document.getElementById("switchh").src = "http://www.sampleweb.com/on.gif";
}
}
}
<div id="main_img">
<img id="lamp" src = "http://www.sampleweb.com/image1.gif">
</div>
<div id="container">
<img id="switchh" src = "http://www.sampleweb.com/on.gif" onclick='change();'>
</div>
</script>
Thank you
/////////////////////EDIT///////////////////////////
Thanks a lot.
Having those two functions there was a result of the previous code, i dont understand how i didnt realize it until you pointed out, heh. (Sleepyness maybe?)
#renuka, that code worked perfectly. I only changed the calling div, from the div "toggle" you created to the div "container" since the button has to switch the images itself, but other than that was sweet. Thanks.
Thanks for the help!
There are a couple of problems here :)
First:
if (document.getElementById("switchh").src = "http://www.sampleweb.com/on.gif")
^ this assigns a variable
You want to change = to === so that a comparison is done
Second, you're creating functions changelamp and changeSwitch but you're never actually calling them. I think you want to get rid of the function declarations completely:
if (vswitch == true){
document.getElementById("lamp").src = "http://www.sampleweb.com/image2.png";
document.getElementById("switchh").src = "http://www.sampleweb.com/off.gif";
} else {
document.getElementById("lamp").src = "http://www.sampleweb.com/image1.gif";
document.getElementById("switchh").src = "http://www.sampleweb.com/on.gif";
}
Finally, there are some minor syntax errors such as missing semi-colons
vswitch = true; // <- like this
Please check the updated code below:
<script type="text/javascript">
function change(){
var vswitch = false;
if (document.getElementById("switchh").src == "http://www.sampleweb.com/on.gif") {
vswitch = true
}
else {
vswitch = false
}
if (vswitch == true){
document.getElementById("lamp").src = "http://www.sampleweb.com/image2.png";
document.getElementById("switchh").src = "http://www.sampleweb.com/off.gif";
}
else {
document.getElementById("lamp").src = "http://www.sampleweb.com/image1.gif";
document.getElementById("switchh").src = "http://www.sampleweb.com/on.gif";
}
}
</script>
<div id="main_img">
<img id="lamp" src = "http://www.sampleweb.com/image1.gif"/>
</div>
<div id="container">
<img id="switchh" src = "http://www.sampleweb.com/on.gif"/>
</div>
<div id="toggle">
<input type="button" value="On/Off" onclick='change();'/>
</div>
The '=' assigns the value to the "src" of the image. Replace it with '==' for comparison.
Additionally from what jasonscript says, you are never switching the vswitch variable to the opposite state, so you'd need to add
vswitch = !vswitch;
after the if in the change() function, that way, the next time you click in the switch, it takes the "other" path through the if
Another point is that if you have the code layout as you have it in your post (script first and then the HTML code) the first if will actually not find the #switchh img, so you need to either move the if inside the change() function or move your script after the HTML
Major problem is that you are unnecessarily creating functions inside script which are never called.
No need for
changelamp() and changeSwitch()
You can directly post the code after the if condition check.
<script> tags should be closed. = assigns and === does comparison, and you need to change the value of vswitch.
Here is a fiddle that accomplishes what you're after with some random images
Related
For a project, I'm trying to highlight the logical fallacy of circular reasoning and have precious few lines of code later to be inserted into a separate webpage.
I am trying to create a simple process of clicking the displayed text to switch back and forth between the two questions. I've tried buttons and it only complicates and make no progress. Half a day gone, still banging my head on desk, as the phrase goes.
I read elsewhere that creating a var tracker facilitates, though I see it only for images, rather than displayed text. It feels like approaching my wits end, but I lack the time to walk away and try again.
This is my code thus far:
<!doctype html>
<head>
<script>
function change() {
var paragraph = document.getElementById("whytrust");
paragraph.innerHTML="I am trustworthy, but how can you be sure?";
}
</script>
</head>
<body>
<p id="whytrust" onclick="change();">You can trust me, but how can you be sure?</p>
</body>
</html>
You need some place to hold the old message so you can put it back again after you toggle the contents.
<!doctype html>
<head>
<script>
var newMsg = "I am trustworthy, but how can you be sure?";
function change() {
var paragraph = document.getElementById("whytrust");
var oldMsg = paragraph.innerHTML;
paragraph.innerHTML = newMsg;
newMsg = oldMsg;
}
</script>
</head>
<body>
<p id="whytrust" onclick="change();">You can trust me, but how can you be sure?</p>
</body>
</html>
This a quick and dirty implementation of what you want. I added a data-textindex attribute to the html element. There I stored an index for the currently shown text. In the javascript I check the current value, update data-textindex and replace it with new text.
function change() {
let paragraph = document.getElementById("whytrust");
let currentlyshown = paragraph.getAttribute('data-textindex');
if(currentlyshown == 0){
paragraph.innerText="I am trustworthy, but how can you be sure?";
paragraph.setAttribute('data-textindex', '1');
}else if(currentlyshown == 1){
paragraph.innerText="You can trust me, but how can you be sure?";
paragraph.setAttribute('data-textindex', '0');
}
}
<p id="whytrust" data-textindex="0" onclick="change();">You can trust me, but how can you be sure?</p>
On a sidenote: You can improve this code a lot. Like storing your text in a json-object. Or maybe using the ternary operator if you are 100% sure there will always be 2 choices. maybe give the function some arguments so you can apply it in a more general scenario.
Try tracking some sort of 'state' for your paragraph -- be it on/off, active/inactive...
Each time the change() function gets called, it doesn't remember what the paragraph was or was supposed to be. So, by setting a state of some sort (in my example a data-state attribute assigned to the paragraph element) the code can know how to behave.
function change() {
var paragraph = document.getElementById("whytrust");
var output = '';
// data-* can be anything, but handy for referencing things
var state = paragraph.getAttribute('data-state');
// check if data-state even exists
if( !state ){
// set it to the default/original state
paragraph.setAttribute('data-state', 'inactive');
state = 'inactive';
}
// toggle the state
// and assign the new text
if( state === 'inactive' ){
paragraph.setAttribute('data-state', 'active' );
output = "I am trustworthy, but how can you be sure?";
}else{
paragraph.setAttribute('data-state', 'inactive');
output = "You can trust me, but how can you be sure?";
}
paragraph.innerHTML = output;
}
<p id="whytrust" onclick="change();">You can trust me, but how can you be sure?</p>
Another option, without tracking state could be hiding and showing the paragraph you want displayed. You don't really need to track state or save the alternating text...
// get the elements from the DOM that you want to hide/show
// you can get tricky and add alternative ways to track
// the paragraph elements, but this works nice for a demo
const whytrust = document.getElementById('whytrust'),
answer = document.getElementById('whytrust-answer');
function change( element ){
// the element parameter being passed is the paragraph tag
// that is present/visible
if( element.id === 'whytrust' ){
answer.className = ''; // clear the .hide class
whytrust.className = 'hide'; // add the .hide class
}else{
whytrust.className = ''; // clear the .hide class
answer.className = 'hide'; // add the .hide class
}
}
.hide{ display: none; }
<p id="whytrust" onclick="change(this);">I am trustworthy, but how can you be sure?"</p>
<p id="whytrust-answer" class="hide" onclick="change(this);">You can trust me, but how can you be sure?</p>
What I like about this solution is that it keeps the content in the HTML and the JavaScript just worries about what to hide/show.
I've just started studying javascript. What I wanna do with the following code is to switch two images as I click the image with id rockImg.
I successfully changed one to another with a single statement of document.getElementById('rockImg').src = "rock_happy.png"; but couldn't swap the two images by clicking the image.
AFAIK, the if-else statement syntax does not have anything wrong; to make sure, I referred this website: https://msdn.microsoft.com/en-us/library/85yyde5c(v=vs.94).aspx.
Is the problem on the comparison statement? Because it works properly when run with ocument.getElementById('rockImg').src = "rock_happy.png" only, this is the only case I can think out.
<html>
<head>
<title>iRock - The Virtual Pet Rock</title>
<script>
function change(){
// alert('yay! it changed!')
if(document.getElementById('rockImg').src == 'rock.png'){
document.getElementById('rockImg').src = "rock_happy.png";
}
else{
document.getElementById('rockImg').src = "rock.png";
}
}
</script>
</head>
<body>
<div style="margin-top:100px; text-align:center;">
<img id="rockImg" src="rock.png" alt="iRock" onclick="change()"/>
</div>
</body>
The src property always returns the entire image URL, not the relative path so the if condition would fail always.
Use setAttribute and getAttribute instead to get exact attribute value
function change(){
var img = document.getElementById('rockImg');
if(img.getAttribute('src') == 'rock.png'){
img.setAttribute('src', "rock_happy.png");
}
else{
img.setAttribute('src', "rock.png");
}
}
You can reduce the number of lines of code by using ternary operator instead of if...else statement.
function change(){
var img = document.getElementById('rockImg');
img.setAttribute('src',img.getAttribute('src') == 'rock.png' ? "rock_happy.png" : "rock.png");
}
I want to click on a link to change the source of an image. Here's what I have come up with so far :
HTML :
click
<div id = "bulb">
<center><img src = "C:\Users\hp\Desktop\on.gif" style = "width:180px;height:270px;position:relative;top:25px;border:2px solid black;"></center>
</div>
JS :
function changesrc() {
var work = document.getElementById('bulb');
if (work.src.match(C:\Users\hp\Desktop\on)) {
work.src = "C:\Users\hp\Desktop\off.gif";
}
else {
work.src = "C:\Users\hp\Desktop\on.gif";
}
}
I am a beginner in javascript, so please help me. According to me, on clicking the a (with text click) the function change src gets executed.that func. has a variable work. the work calls the element by id = bulb. If that variable's(work's) src matches that of the image on my desktop(with the bulb on
) then it gets changed to off else it changes to on(as if it isn't on that means it's off and so we change that).
I took help from w3schools. I looked up similar questions. I even changed work.src to bulb.src . Still cant find my mistake. Please help and tell me what's causing this!!! No jQuery please as I don't know it yet.
document.getElementById('bulb') is not an image. In your code you are changing the "src" of the <div>.
Change the id to the image, like:
click
<div style="text-align:center;"">
<img id="bulb" src="http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/se/se-logo-med.png?v=d9b0b6647f17" style="width:180px;height:270px;position:relative;top:25px;border:2px solid black;">
</div>
And Javascript:
function changesrc(){
var work = document.getElementById('bulb');
if(work.src.indexOf('se/se-')){
work.src = 'http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo-med.png?v=6f86a5fa447f';
}
else{
work.src = 'http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/se/se-logo-med.png?v=d9b0b6647f17';
}
}
Update:
"return" corrected: onclick="changesrc(); return false;".
if (work.src.match(C:\Users\hp\Desktop\on)) {
This should be matching a string?
if (work.src.match('C:\Users\hp\Desktop\on')) {
You're using the match function which expects a RegExp as a parameter. Actually I think that in your case you could just compare the strings:
if (work.src === 'C:\Users\hp\Desktop\on') {
function normToggle(){
document.getElementById('normToggle').onclick = function(){
if(document.getElementById('normToggle').checked){
document.getElementsByTagName('add').style.verticalAlign= 'baseline';
}else{
document.getElementsByTagName('add').style.verticalAlign= 'super';
}
};
document.getElementsByTagName('add').style.verticalAlign= 'super';
document.getElementById('normToggle').checked = false;
}
So I try to use a checkbox to change the style of the 'add' tags. Their vertical align are super first, then i wnat them to change normal, but they didnt respond. Another javascript from the smae file working just fine.
getElementsByTagName returns a HTML Collection - you'll need to iterate through the collection to change the style of each element in the collection
something like this:
function normToggle() {
var setAlign = function (align) {
[].forEach.call(document.getElementsByTagName('add'), function(tag) {
tag.style.verticalAlign = align;
});
}
document.getElementById('normToggle').addEventListener('click', function() {
setAlign(this.checked ? 'baseline' : 'super');
});
setAlign('super');
document.getElementById('normToggle').checked = false;
}
Looking at the code now, you're unlikely to have elements called <add> !!! Is that some sort of mistake in your HTML?
In Javascript, I'm trying to create a user script that will automatically click on a 'Blue Button'. Normally, I would do this:
var bluebutton = "document.getElementById("blue_button")"
if (bluebutton) {
bluebutton.onclick();
}
But NOW, the blue button does not have its own obvious ID. It's ID is randomized, and could be either button1, button2, or button3.
Here's the HTML that I'm talking about:
<div class="button_slot">
<div id="button1" style="cursor:pointer; padding-left:30px" onclick="buttonsubmit('button1')" onmouseover="infopane.display('Blue Button','I'm a blue button!')" onmouseout="infopane.clear()">
<div class="button_slot">
<div id="button2" style="cursor:pointer; padding-left:30px" onclick="buttonsubmit('button2')" onmouseover="infopane.display('Red Button','I'm a red button!')" onmouseout="infopane.clear()">
<div class="button_slot">
<div id="button3" style="cursor:pointer; padding-left:30px" onclick="buttonsubmit('button3')" onmouseover="infopane.display('Yellow Button','I'm a yellow button!')" onmouseout="infopane.clear()">
After a bit of reading, I've concluded that the only way to direct my onclick() to the correct element/string is by using ".toString().match(name)" as shown below:
function clickbutton(name) {
var button_list = document.querySelectorAll('.button_slot > div');
for (var i=0; i<button_list.length; i++) {
var button = button_list[i];
if (button.onmouseover && button.onmouseover.toString().match(name)) {
button.onmouseover();
button.onclick();
break;
}
}
}
clickbutton('Blue');
(note: sometimes I use clickbutton('Red'); or clickbutton('Yellow'); just to experiemen)
Now here's the problem. This method works so horribly... Sometimes, my script completely misses the button (as in, nothing gets clicked) EVEN THOUGH there is definitely a string with the word 'Blue' in it.
If someone could identify what I'm doing wrong, or perhaps even suggest a more effective method, I would appreciate it so much! Thank you!
First, I'm not sure why you can't give each button an ID which corresponds to it's color, because I believe that would be the easiest way to achieve this. But assuming that, for some reason, your button ID's must be randomized (or for that matter, maybe they don't even have an ID).
In this case, what I would do is give each button a data-button-type attribute, for instance:
<div data-button-type="Blue" id="..." style="..." onclick="..." onmouseover="..." onmouseout="...">
Now, I can check the attribute when looking for which button to click, for example:
function clickbutton(name) {
var button_list = document.querySelectorAll('.button_slot > div');
for (var i=0; i<button_list.length; i++) {
var button = button_list[i];
if (button.getAttribute('data-button-type') == name) {
button.onmouseover();
button.onclick();
break;
}
}
}
clickbutton('Blue');
I'm pretty sure you want to use indexOf although I think its most likely a timing issue.
First just try invoking it in a setTimeout function, so the document has (probably) loaded fully when you execute. It would explain it sometimes working sometimes not.
setTimeout(function(){ clickbutton(name) }, 3000);
I would do:
var clickButton = function(name){
var button_list = document.querySelectorAll('.button_slot > div');
for(var i = 0; i < button_list.length; i++){
var button = button_list[i];
if(button.getAttribute('onmouseover').indexOf(name) !== -1){
button.onclick.apply(); // They seem to have parameters in your example?
}
break;
}
}
setTimeout(function(){ clickButton('blah') }, 3000);
As a first attempt...