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') {
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 am making a price estimator.
How would correctly write a jQuery function that checks a variable and depending on that amount hides/shows a certain div element accordingly.
So if I had:
a HTML div with the ID 'Answer'
<div id="answer">Hide Me</div>
$("#answer")...
a variable (this variable would change)
var x = 30
Now I know the css to hide the div would be:
#answer{
visibilty:hidden;
}
What would be the correct way to hide the function checking these certain parameters? for example if x > 20 then hide etc
Now I know there will be many ways to do this and they may not require jQuery, please inform me if this is the case. Perhaps it just needs JS. I know there will be many ways to do it not just one so if you have a different way please comment as I am keen to learn.
Any help would be greatly appreciated.
Cheers
F
Note that you can also remove or add a class:
$('#answer').removeClass('hide');
$('#answer').addClass('hide');
But what you want to do is $('#answer').hide(); or $('#answer').show();
Execute this function providing the variable v:
var checkVar = function(v) {
var target = $('#answer');
if (parseInt(v) > 20) {
target.hide();
} else {
target.show();
}
}
For example, if the variable comes form a selection:
$('#selectId').on('change', function() {
checkVar($(this).val());
});
Remove the CSS. You can do it in jQuery
if(x>20){
$('#answer').hide();
}
You can use this one
$("#answer").hide();
#kapantzak's answer looks good. But keep your logic and style separated and if your not going to use the variable for the actual element twice, I wouldn't make it. So go:
var checkVar = function(var) {
var element = $('#answer');
if (parseInt(var) > 20) {
element.addClass('hidden');
}else{
element.removeClass('hidden');
}
}
And in your CSS go:
#answer.hidden{
display: none;
}
Also, depending on your preference, display: none; doesn't display anything of the object whereas visibility: hidden hides the object but the space the object was occupying will remain occupied.
HTML
<input id="changingValue">
...
<div id="answer">Hide Me</div>
CSS (not mandatory if you check values on loading)
#answer{ display:none;}
JS
var limit = 20;
$(function(){
$("#changingValue").change(function(){
if(parseInt($("#changingValue").val())<limit) { $("#answer").show(); }
else { $("#answer").hide(); }
});
});
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
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...
I have a question about how to read the string betweena tag, for example.
Devices connecting to HOME <a onclick="kmt_Toggle('BOX01', this)" class="cs_answer_link" value="[Show me how to download and install my map..]">[Show me how to download and install my map..]</a><br />
<br />
<div class="cs_answer_secondAccordion" id="BOX01" style="display: none;">
Steps for downloading and installing a map...
</div>
My code a simple, when users click on the a tag, the div class will show, and change Show me how to download and install map string in a tag to Close. When users click again, the current "close" will become "original long text". My main issue is that How i can read the string between a tag, thanks. I can not use JQuery
function kmt_Toggle(obj, aTag) {
var el = document.getElementById(obj);
if ( el.style.display != 'none' ) {
el.style.display = 'none';
//var tagString=document.ge(aTag).valueOf();
// aTag.innerHTML='[more..]';
aTag.innerHTML= tagString;
}
else {
el.style.display = '';
aTag.innerHTML='[close..]';
}
}
Hello Guys, thanks.
I think i have not made my question crystal clear. I want to build a toggle function in this Javascript, if people clicks on a tag, for instance,
<a onclick="kmt_Toggle('BOX01', this)" class="cs_answer_link" value="[Show me how to download and install my map..]">[Show me how to download and install my map..]</a>
It will show my div if my div has style = none; and change Show me how to download and install map into "close"
Steps for downloading and installing a map...
If people click on the link again, it will go back to the "show me how to download and installl map" and hide my div.
I tried to build something by following idealmachine solution. It does not work.
Cheers,
Qing
You can use:
getElementsByTagName("tagName")[0].firstChild.nodeValue;
or:
getElementsById("id")[0].firstChild.nodeValue;
First of all, the value attribute of an a element is not officially standardized by the W3C. You don't need it.
That said, some lines of code that might work are:
// innerHTML way
aTag.originalInnerHTML = atag.innerHTML; // to save the innerHTML
aTag.innerHTML = '[close..]'; // to add new link text
aTag.innerHTML = aTag.originalInnerHTML; // to restore the innerHTML
// W3C DOM way
// Save
var cur = aTag.firstChild;
aTag.oldChildNodes = [];
while(cur) {
aTag.oldChildNodes.push(cur);
cur = cur.nextSibling;
}
// Add new link text
while(aTag.lastChild) aTag.removeChild(atag.lastChild);
aTag.appendChild(document.createTextNode('[close..]'));
// Restore
while(aTag.lastChild) aTag.removeChild(atag.lastChild);
for(var i = 0; i < aTag.oldChildNodes.length; ++i) {
aTag.appendChild(aTag.oldChildNodes[i]);
}
Or you could do either of these instead, similar to how you are switching the accordion sections on and off:
Insert both link texts into the HTML, then use CSS display: none; to switch off the one you do not want.
Switch between entire a elements using CSS display: none;.
you can use the
documentElement. getElementsByTagName( "div" )
you have do define after if you want the first element or second etc
like so
documentElement. getElementsByTagName( "div" ).item(0).innerHtml;
will give you the innehtml of the first occurance of div
or if you have an id
documentElement. getElementsById('idname')
Maybe:
return document.getElementById(<your div name>).innerHtml;
I found out a way. I change my javascript like that
function kmt_Toggle(obj, aTag) {
var el = document.getElementById(obj);
//Save original Store at the firs time.
if(!aTag.originalInnerHTML)
{
aTag.originalInnerHTML=aTag.innerHTML;
}
if (el.style.display != 'none' ) {
el.style.display = 'none';
aTag.innerHTML= aTag.originalInnerHTML;
}
else if( el.style.display =='none'){
el.style.display = '';
aTag.innerHTML='[close..]';
}
}"
//First I store aTag text string into a variables