JavaScript cannot change image using attr - javascript

My html code here is to click next and change the graph.
I have put 1.jpg, 2.jpg, 3.jpg, and html file into same file.
My question is that I want to change my graph by the code $("#page1").attr("src", fname);.
But it cannot do it at all. It always shows 1.jpg.
<script>
var order = new Array('1.jpg', '2.jpg', '3.jpg');
var trial = 0; //current trial
document.write("STRING:");
$(document).ready(function(){
ShowImage(trial);
});
function ShowImage(t) {
$("#page1").show();
var N = t+1; //counting from 1
$(".progress").text('('+N+'/'+order.length+')');
}
function NextImage() {
current = current + 1;
$("#page1").hide();
var fname=order[current];
$("#page1").attr("src", fname);
});
ShowImage(current);
}
</script>
<style> .page {display: none;} </style>
<div class="page" id="page1">
<img src=1.jpg><br>
<input type=radio name=f1 value=T> T
<input type=radio name=f1 value=F> F <br>
Next
<span class="progress"></span>
</div>
<div class="page" id="page2">
<h3>All done!</h3>
</div>```

you're going to change src of <img> tag, so you should get the <img> tag.
in your html the <img> tag is in <div id="page1"> so you should use the find keyword to get the <img> tag and then change the src of it.
function NextImage() {
current = current + 1;
$("#page1").hide();
var fname=order[current];
$("#page1").find('img').attr("src", fname); //this line should find the img tag and then change the src attr
});
ShowImage(current);
}

Related

How to set order to arrays when I click next and previous on JavaScript?

I want to create a image viewer where you click next and previous to change the image.
So far the buttons next and previous changes the image. However when I click next then previous, the image doesn't go to the previous image instead it goes to the starting image.
My guess is to create a variable var = newImage and use that variable on function change2() and create a new varirable var= newImage2 and use that on function change().
is that possible?
<!DOCTYPE html>
<html>
<head>
<title>JS ChangeImage</title>
</head>
<body>
<h1 align="center">Change Image</h1>
<br>
<div class= "container" align="center">
<button onclick="change2()">Previous</button>
<img src="html5.png" style="height: 500px; width: 500px" id="changeimg">
<button onclick="change()">Next</button>
</div>
</body>
<script>
var img=0;
var imgArr = ["html5.png","css3.png","javascript.png"]
function change() {
var image = document.getElementById('changeimg');
console.log("current image =>", imgArr[img])
document.getElementById('changeimg').src =imgArr[img];
if (img== 2) img = 0;
else
img++;
}
function change2() {
var c1=
document.getElementById('changeimg').src =imgArr[img];
console.log("current image =>", imgArr[img])
if (img== 0) img = 2;
else
img--;
}
First, I noticed that you are changing the img variable after assigning the image to the element. I think you should switch the order. The way it is now, when you click Next, the number advances, but the picture is associated with the previous number. If you then click Previous, the number will reduce, but the image will appear to advance.
I've made some other changes for simplicity here:
HTML:
<h1 align="center">Change Image</h1>
<br>
<div class= "container" align="center">
<button onclick="change(event)" name='1'>Previous</button>
<img src="html5.png" style="width: 500px" id="changeimg">
<button onclick="change(event)" name='2'>Next</button>
</div>
JS:
var currentImg = 0;
const imgArr = ["html5.png","css3.png","javascript.png"]
const change=(event)=>{
if(event.target.name==='1'){
currentImg>0?currentImg--:currentImg=2;
} else if(event.target.name==='2'){
currentImg<imgArr.length-1?currentImg++:currentImg=0;
}
console.log(currentImg);
document.getElementById('changeimg').src = imgArr[currentImg];
}
Please note the use of the 'name' attribute of the for use in the logic of the change function. This allows me to use only one function for both buttons. I hope this helps.

Change image onclick with div toggle

I have some code I'm working on that toggles a div of information depending on the user clicking an image. What I'm looking for is assistance in getting the image to swap when the user clicks, then to swap back when it's clicked again. The image should be changing to: https://casetest.blackboard.com/bbcswebdav/users/kas200/collapse.gif
I'm a newbie when it comes to coding with JS, so any help provided would be much appreciated!
<script type="text/javascript">
function toggleMe(a){
var e=document.getElementById(a);
if(!e)return true;
if(e.style.display=="none"){
e.style.display="block";
}
else{
e.style.display="none";
}
return true;
}
</script>
<input type="image" src="https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif" onclick="return toggleMe('para1')" value="Toggle"><br>
<div id="para1" style="display:none">
This is my text for section 1!
</div>
<br>
<input type="image" src="https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif" onclick="return toggleMe('para2')" value="Toggle"><br>
<div id="para2" style="display:none">
This is my text for section 2!
</div>
<br>
<input type="image" src="https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif" onclick="return toggleMe('para3')" value="Toggle"><br>
<span id="para3" style="display:none">
This is my text for section 3!
</span>
You've got the right idea. What I did for this case was add an id to each image with the name of the div + _img -- grabbed that element the same way, then updated the src:
javascript
function toggleMe(a){
var e=document.getElementById(a);
var i=document.getElementById(a+'_img');
if(!e)return true;
if(e.style.display=="none"){
i.src="https://casetest.blackboard.com/bbcswebdav/users/kas200/collapse.gif"
e.style.display="block"
}
else{
i.src="https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif"
e.style.display="none"
}
return true;
}
html
<input type="image" src="https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif" onclick="return toggleMe('para1')" value="Toggle" id="para1_img"><br>
<div id="para1" style="display:none">
This is my text for section 1!
</div>
<br>
<input type="image" src="https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif" onclick="return toggleMe('para2')" value="Toggle" id="para2_img"><br>
<div id="para2" style="display:none">
This is my text for section 2!
</div>
<br>
<input type="image" src="https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif" onclick="return toggleMe('para3')" value="Toggle" id="para3_img"><br>
<span id="para3" style="display:none">
This is my text for section 3!
</span>
here's a working example: http://jsfiddle.net/8h4T7/1/
PURE CSS
There's no need to use JS.
Here you go with a simple HTML / CSS solution:
LIVE DEMO
<input id="_1" class="toggler" type="checkbox">
<label for="_1"></label>
<div>This is my text for section 1!</div>
CSS:
.toggler,
.toggler + label + div{
display:none;
}
.toggler + label{
background: url(https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif);
position:relative;
display:inline-block;
width:11px;
height:11px;
}
.toggler:checked + label{
background: url(https://casetest.blackboard.com/bbcswebdav/users/kas200/collapse.gif);
}
.toggler:checked + label + div{
display: block;
}
The good part is that both your images are loaded in the browser so there won't happen an useless image request to the server (creating a time-gap) with no image visible (while it's loading).
As you can see the trick is to hide the checkbox and the div,
than using the :checked state you can do your tricks.
PURE JS
If you really want to play with JS than here's some changes to simplify the HTML markup:
<input type="image" src="https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif" value="para1"><br>
<div id="para1" style="display:none">This is my text for section 1!</div>
Note that I've changed the useless value to something useful, and removed the unnecessary ID from your inputs. Also, I've removed the messy HTML inline onclick callers. They're hard to maintain in production.
The input value will now help us to target your ID containers.
var imgSRC = "//casetest.blackboard.com/bbcswebdav/users/kas200/";
function toggleFn(){
var tog = this.tog = !this.tog;
var targetEl = document.getElementById(this.value);
targetEl.style.display = tog ? "block" : "none";
this.src = imgSRC + (tog?"collapse":"expand") + ".gif";
}
var $para = document.querySelectorAll("[value^=para]");
for(var i=0; i<$para.length; i++) $para[i].addEventListener('click', toggleFn, false);
LIVE DEMO 1
Another JS version:
var imgSRC = "//casetest.blackboard.com/bbcswebdav/users/kas200/";
function toggleFn(){
var el = document.getElementById(this.value);
el.style.display = el.style.display=='none' ? "block" : "none";
this.src = imgSRC +(this.src.match('expand') ? "collapse" : "expand")+ ".gif";
}
var $para = document.querySelectorAll("[value^=para]");
for(var i=0; i<$para.length; i++) $para[i].addEventListener('click', toggleFn, false);
LIVE DEMO 2
jQuery VERSION
Having the exact same as above HTML this is the needed jQuery code:
var imgSRC = "//casetest.blackboard.com/bbcswebdav/users/kas200/";
$(':image[value^="para"]').click(function(){
var tog = this.tog = !this.tog;
$('#'+ this.value).fadeToggle(); // or use .slideToggle();
this.src = imgSRC + (tog?"collapse":"expand") + ".gif";
});
LIVE DEMO
The interesting part of the code above is the way we store the current state directly into the this element reference Object:
var tog = thistog = !this.tog;
and using a set negation we create the toggle state.
Instead, if you're familiar with the bitwise XOR operator you can use it (to achieve the same) like:
var tog = this.t ^= 1;
XOR DEMO
Using jQuery
You can also use jQuery. It's a tool designed to help young coders. It allows manipulation of JavaScript through minimal functions.
Adding <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> to the head of your document will allow you to use jQuery. Then you can add some style to your collapsibles like this method based on pennstatephil's code.
function toggleMe(a){
var e=$('#'+a);
var i=$(a+'_img');
if(!e) return false;
if(e.css('display') == "none" ) {
i.attr('src', 'https://casetest.blackboard.com/bbcswebdav/users/kas200/collapse.gif');
e.fadeIn('slow');
}
else {
i.attr('src', 'https://casetest.blackboard.com/bbcswebdav/users/kas200/expand.gif');
e.fadeOut('fast');
}
return true;
}
And an example can be seen here
jQuery API Documentation can be found here

Show div and hide siblings when clicking on div

I am having a lot of trouble figuring out how to write the appropriate javascript or jquery to show a specific div when my clickable div is clicked, meanwhile hiding all other divs within the same class that were previously clicked.
HTML
<img src="images/Current system & actors.jpg" alt="" usemap="#Map" style="left:275px; position:absolute; top:247px; width:100%; z-index:1; " usermap="#mymap" >
<div id="items" >
<div class="sqtrigger" id="xcrudeoil" style="position:absolute; left:200px; top:200px; " onclick="MM_showHideLayers('crudeoil','','show')" ></div>
<div class="sqtrigger" id="xNP" style="position:absolute; left:300px; top:200px; " onclick="MM_showHideLayers('NP','','show')" ></div>
</div>
<div id="info" >
<div id="crudeoil" class="textbox" >Crude oil description </div>
<div id="NP" class="textbox" >NP description</div>
</div>
JAVASCRIPT
function MM_showHideLayers() { //v9.0
var i,p,v,obj,args=MM_showHideLayers.arguments;
for (i=0; i<(args.length-2); i+=3) {
with (document) if (getElementById && ((obj=getElementById(args[i]))!=null)) {
v=args[i+2];
if (obj.style) {
obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v;
}
obj.visibility=v;
}
}
}
I've found information on doing this with <area> tag however I'd like to avoid rewriting my clickable divs to areas within my map because I have over 100 clickable divs and need a work around solution for now...
Example --> http://jsfiddle.net/berqK/4/
var links = document.getElementById('oshastatemap');
for (var i = 0; i < links.children.length; i++) {
links.children[i].onclick = function(ev) {
target_id = this.id.replace('x', '');
s = document.getElementById(target_id);
states = document.getElementsByClassName('show');
for (var j = 0; j < states.length; j++) {
states[j].className = '';
}
s.className = 'show';
};
}
So, how can I adjust this code I've found for showing a div when a link is clicked, to showing a div when a div is clicked while still hiding the others?
In reference to my divs ...
How can I make id="xcrudeoil" show id="crudeoil" (and xNP show NP) while at the same time hiding all child divs of div id=info (or within class="textbox")?
Here is an sample of what I have working so far. (note: in my browser the divs appear but I can't see them in fsfiddle): http://jsfiddle.net/ZCantrall/Ru82F/6/
Thanks a lot in advance! I'd really appreciate ANY advice that you can offer.
*EDIT // Second attempt with the CSS from /jsfiddle.net/Ru82F/7/ and the following HTML & JS
<html><head>
<title>IES</title>
<link href="IES.css" rel="stylesheet" media="screen" type="text/css" >
</head>
<body>
<div id="items" >
<div class="sqtrigger" id="xcrudeoil" >Oil</div>
<div class="sqtrigger" id="xNP" >NP</div>
</div>
<div id="info" >
<div id="crudeoil" class="textbox" >Crude oil description </div>
<div id="NP" class="textbox" >NP description</div>
</div>
<script> src="jquery-1.9.1.js" </script>
<script> src="jquery-migrate-1.1.0.js" </script>
<script>
$('.sqtrigger').on('click', function(e) {
var targetId = this.id.replace('x', '');
$('#info .textbox').hide();
$('#' + targetId).show();
});
</script>
</body></html>
This small jQuery script will show the relevant div and hide the others when you click the triggers (there might be issues with the css, I removed it for this test):
$(document).ready(function() {
$('.sqtrigger').on('click', function(e) {
var targetId = this.id.replace('x', '');
$('#info .textbox').hide();
$('#' + targetId).show();
});
});
http://jsfiddle.net/Ru82F/7/
Could you please try this... http://jsfiddle.net/berqK/22/
JQuery Code...
var links = document.getElementById('oshastatemap');
for (var i = 0; i < links.children.length; i++) {
links.children[i].onclick = function(ev) {
target_id = this.id.replace('State', 'Layer');
$("div[Id^='Layer']").css('display','none');
$('#'+target_id).show();
};
}
This small jQuery script will show the relevant div and hide the others
$("target_div").nextAll().hide()
$("target_div").prevAll().hide()

Show/hide element based on clicked href of link

I am new to JavaScript and actually quite desperate by now
I have an HTML file that:
gets data from an XML file and displays them in various divs (e.g. )
these divs are hidden (by default) by a class name (class='box')
when a link is clicked, I pass the 'href' to the function showContent, remove the #, and then look for an element with that ID in the document.
then I add a new class name ('show') - so that this element shows up!
If you run the code you will see that every time you click on a link a new div is displayed...
So current problems:
replace already shown divs with the new clicked ID so that only one div shows up every time.
How can I avoid inserting the onClick event in every single tag - and make this more automated?
My code is as follows:
function showContent(obj)
{
var linkTo = obj.getAttribute("href");
var newlinkTo=linkTo.replace('#','');
//alert (newlinkTo);
document.getElementById(newlinkTo).innerHTML=" This is where the xml variable content should go";
document.getElementById(newlinkTo).className += " Show";
return true;
}
<a href="#b0" onClick="return showContent(this);">
<div id="text_content"> link2 </div>
</a>
<a href="#b1" onClick="return showContent(this);">
<div id="text_content"> link 1 </div>
</a>
<div class='box' id='b0'> abstract content </div>
<div class='box' id='b1'> introduction content </div>
I'm not usually into using jQuery everywhere, but with it you could just do:
<a class='showContent' data='b0'/>
Your js:
var selected;
$('a.showContent').on('click',function(e){
var toShow = $(this).attr('data');
if(selected!==undefined) selected.removeClass('Show');
selected = $(div+'#'+toShow);
selected.addClass('Show');
});
Not sure if this is what you want, but thought I'd suggest it.
This sort of thing is not hard to do without jQuery.
I would recommend using a hash-bang (#!) for Javascript activated links to keep it separate from other possible links with hashes. (script is at the bottom)
<div id="nav-links">
<a href="#!b0">
<div id="text_content"> link2 </div>
</a>
<a href="#!b1">
<div id="text_content"> link 1 </div>
</a>
</div>
<div class='box' id='b0'> abstract content </div>
<div class='box' id='b1'> introduction content </div>
<script type="text/javascript">
var links = document.getElementById('nav-links').getElementsByTagName('a');
for(var i = 0, link; link = links[i]; i++) {
link.onclick = showContent;
// Hide content divs by default
getContentDiv(link).style.display = 'none';
}
// Show the first content div
if(links.length > 0) showContent.apply(links[0]);
var current;
function showContent() {
// hide old content
if(current) current.style.display = 'none';
current = getContentDiv(this);
if(!current) return true;
//current.innerHTML = "This is where the xml variable content should go";
current.style.display = 'block';
return true;
}
function getContentDiv(link) {
var linkTo = link.getAttribute('href');
// Make sure the link is meant to go to a div
if(linkTo.substring(0, 2) != '#!') return;
linkTo = linkTo.substring(2);
return document.getElementById(linkTo);
}
</script>​
There is a WAY cleaner way to do this:
This is just my quick example, it can get EVEN cleaner than this, but this works for your case:
HTML:
link b0
link b1
<div class='box' id='b0'> abstract content </div>
<div class='box' id='b1'> introduction content </div>​​​​​​​​​
CSS:
#b0 { display: none; }
#b1 { display: none; }
a, div.text_content { display: inline; padding: 0 10px; }
JQUERY:
​$('.link').click(function(){
var id = $(this).attr("rel");
$('#'+id).slideToggle('slow');
});
​
Each link would have to have a REL attribute that is the same as the ID of the div element that you are trying to show.
Here is a JSFiddle to this example in action:
http://jsfiddle.net/CUJSM/5/

click on image and change a text

U have 2 images on a page and a textbox (php)
When u click on the image i want to change the text.
I am a starter, please sent a code that isn't to hard to understand.
<body>
<img src="bier1.jpg" alt="u mad" onclick= "">
<img src="bier2.jpg" alt="u mad" onclick= ""><br>
<form>
<input type="text" name="Example"/>
</form>
</body>
Are I'm right that you want to change the text of the Textbox? If yes here's the code:
<body>
<img src="bier1.jpg" alt="u mad" onclick= "document.forms[0].elements['Example'].value = 'Image 1'">
<img src="bier2.jpg" alt="u mad" onclick= "document.forms[0].elements['Example'].value = 'Image 2'"><br>
<form>
<input type="text" name="Example"/>
</form>
</body>
You'll need to use Javascript, I prefer to give javascript code using jQuery, so please do a quick Google search on jQuery.
<script type="text/javascript">
$(function(){
//You need to bind click events to your images and probably
$("img.has-message").click(function(){
var msg = $(this).attr("data-msg");
//get the message from that particular image
$("#text_box_id").attr("value",msg);
//changes the value of the text box to display the message
return false;
});
});
</script>
So you place this code in the <head></head> tag of your page
This code will work perfectly assuming you could change your HTML to look like so:
<body>
<img src="bier1.jpg" alt="u mad" class="has-message" data-msg="message to be displayed when the image is clicked">
<img src="bier2.jpg" alt="u mad" class="has-message" data-msg="message to be displayed when the image is clicked"><br>
<form>
<input type="text" id="text_box_id" name="Example"/>
</form>
</body>
Please remember that jQuery needs to have been included on your page for the above to work.
You need to first add id to the text field:
<input type="text" name="Example" id="myTextBox" />
Then you can do such thing:
<img src="bier1.jpg" alt="u mad" onclick="document.getElementById('myTextBox').value = this.alt;" />
<img src="bier2.jpg" alt="u mad" onclick="document.getElementById('myTextBox').value = this.alt;" />
This is not very elegant though, you have it applied to all images without having to change the markup, have such JavaScript:
window.onload = function() {
var oTextbox = document.getElementById('myTextBox');
for (var i = 0; i < document.images.length; i++) {
document.images[i].onclick = function() {
oTextbox.value = this.alt;
};
}
};
Live test case of above code.
You can also have the above code work only for certain images by applying a class to those images you want "clickable", for example:
<img src="bier1.jpg" alt="u mad" />
<img class="clickable" src="bier2.jpg" alt="u mad 2" />
To have only the second cause the textbox to change, have such code:
window.onload = function() {
var oTextbox = document.getElementById('myTextBox');
for (var i = 0; i < document.images.length; i++) {
var image = document.images[i];
if (image.className === "clickable" || image.className.indexOf("clickable ") >= 0 || image.className.indexOf(" clickable") >= 0) {
image.onclick = function() {
oTextbox.value = this.alt;
};
}
}
};​
Updated fiddle to demonstrate.
I am guessing they mean the page is served as a php page. I would do this purely in javascript. In pseudo code I would do the following.
Create function in javascript
Function looks up input using name
Function sets the text of the input to whatever you like (this could be based on which image was clicked
Id deffinately suggest looking at w3schools website which will give you lots of simple examples to get you started.
Also start basic and work your way up, if you cant get it all working at once, do it bit by bit, get your onclick to alert when you click it, then try setting the text once you knwo your onclicks are working.

Categories