Function using <a> - javascript

I have to make the following images to switch between them when I click in the <a> link but it didn't work. When I put the 'onclick' reference in the image it works but not in the link.
Here is the code:
var images=Array("1.png","2.jpg","3.png");
var visibleImage=0;
var a = document.getElementById("link");
function change(img)
{
visibleImage++;
if(visibleImage>=images.length)
{
visibleImage=0;
}
img.src=images[visibleImage];
}
The image look like this:
<img src="1.png" onclick="change(this);">
The href link is this:
Click to change

You are changing the src attribute of this, which is the element you currently interact with (which is <a>). You could pass document.getElementById('image') in the function, but I think it is better to get it in the function.
Not changing your function:
var images=Array("1.png","2.jpg","3.png");
var visibleImage=0;
var a = document.getElementById("link");
function change(img)
{
visibleImage++;
if(visibleImage>=images.length)
{
visibleImage=0;
}
img.src=images[visibleImage];
console.log(img.src);
}
<img src="1.png" onclick="change(this);" id='image'>
Click to change
A more understandable function:
var images=Array("1.png","2.jpg","3.png");
var visibleImage=0;
var a = document.getElementById("link");
function change()
{
img = document.getElementById("image");
visibleImage++;
if(visibleImage>=images.length)
{
visibleImage=0;
}
img.src=images[visibleImage];
console.log(img.src);
}
<img src="1.png" onclick="change();" id='image'>
Click to change

This in <img> tag is passing itself as a value to the function and because of that it executes without any problem, doing so with an <a> tag would pass the anchor tag to the function change.
You should look into Firebug on Mozilla, or plain old 'inspect element' in Chrome's — and some other browsers' — right-click context-menu, to debug the JavaScript and visualize what is being passed as an argument.

If I were you, I would use addEventListener...
var images = [
'http://i3.kym-cdn.com/photos/images/newsfeed/000/170/791/welcome-to-the-internet-internet-demotivational-poster-1264714433.png.jpg',
'https://s-media-cache-ak0.pinimg.com/736x/a5/98/1f/a5981fcc09689034ec9dc9201c9787f5.jpg',
'http://s2.quickmeme.com/img/b3/b3bd9df9b60b8abc7f1253908756964c37e17262e6df6be51bc4a528183e2c96.jpg'
];
var visibleImage = 0,
a = document.querySelector('a'),
img = document.querySelector('img');
a.addEventListener('click', change, false);
function change() {
visibleImage++;
if(visibleImage >= images.length) {
visibleImage = 0;
}
img.src = images[visibleImage];
}
Click to change
<hr>
<img src="http://i3.kym-cdn.com/photos/images/newsfeed/000/170/791/welcome-to-the-internet-internet-demotivational-poster-1264714433.png.jpg">

Related

How to toggle images

I am a programming fool,
All I need is to be able to toggle two images, one which acts as the 'up state' of a button and then 'onclick' the second image appears and remains until it is clicked again whereby it is replaced by the the 'upstate image'.
Please don't mock me for this pitifull attempt which fails miserably. Here is my code.
function change() {
if (window.document.pic.src == "imgd1.svg"){
window.document.pic.src ="imgd1over.svg";
}
else if(window.document.pic.src == "imgd1over.svg"){
window.document.pic.src ="imgd1.svg";
}
<img src ="imgd1.svg" name ="pic" id = "test" onclick ="change()"/>
Thank you in anticipation.
Check this demo.
function change(image) {
if (image.src.indexOf("imgd1.svg") > -1){
image.src ="imgd1over.svg";
}
else{
image.src ="imgd1.svg";
}
}
In the fiddle case the image.src wasn't just the image's name, but the full url: http://fiddle.jshell.net/_display/imgd1.svg. So I have used indexOf() to check if the image's source constains the string you want.
Besides, I have changed the way change() function references to the image:
<img src ="imgd1.svg" name ="pic" id = "test" onclick ="change(this)"/>
Using change(this) will set the own image as the first parameter of the event, so you don't need to get it in the window object or event with getElementById or whatever.
function change() {
var image = document.getElementById("test");
if (image.src.indexOf("imgd1.svg") > -1 ){
image.src = "imgd1over.svg";
}
else if(image.src.indexOf("imgd1over.svg") > -1 ){
image.src = "imgd1.svg";
}
}
Here is the working code:
<img src ="imgd1.svg" name="pic" onclick="change();"/>
<script>
function change() {
if (window.document.pic.src == "imgd1.svg"){
window.document.pic.src ="imgd1over.svg";
}
else if(window.document.pic.src == "imgd1over.svg"){
window.document.pic.src ="imgd1.svg";
}
}
<script>
See the full demo:
http://jsfiddle.net/jswsze5q/
Try this:
<script>
function change() {
var img1 = "imgd1.svg",
img2 = "imgd1over.svg";
var imgElement = document.getElementById('test');
imgElement.src = (imgElement.src === img1)? img2 : img1;
}
</script>
<img src="imgd1.svg" id="test" onclick="change();"/>
Example: jsfiddle
Try using Jquery
var flag = 0;
function change(){
if(flag){
$("#img").attr("src","img1.png");
flag = 0;
}
else{
$("#img").attr("src","img2.png");
flag = 1;
}
}
Simplest toggle option
where variable flag acts as flag which detects which image is active
img is the id of image control.
Code to include Jquery from google CDN
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

can i identify a link that have an imag with certain href

I am working on a web application, and i need to adjust a People Picker dialog height. currently to keep firing the script when the user open/close the dialog , i set a timer (2 seconds for the script to run), as follow:-
var interval = null; //Defines the start interval variable
$(document).ready(function () { // jQuery needed for this
/* People Picker Fix Starts */
if (navigator.appVersion.indexOf("MSIE 10") > -1) { // IE 10 Specific condition for People Picker Bug
interval = setInterval(adjustPeoplePicker, 2000);
}
/* People Picker Fix Ends */
});
function adjustPeoplePicker() {
if ($('.ms-dlgFrame').contents().find('#resultcontent').length > 0) {
$('.ms-dlgFrame').contents().find('#resultcontent').css('height', '350px');
$('.ms-dlgFrame').contents().find('#MetadataTreeControlTreeSearch').css('height', '350px');
//clearInterval(interval);
}
}
here is the realted markup for the dialog to open:-
<a id="ctl00_ctl41_g_a4fb58d0_ad0d_40cf_a4a3_ccabea410e43_ff141_ctl00_ctl00_UserField_browse" href="javascript:" onclick="__Dialog__ctl00_ctl41_g_a4fb58d0_ad0d_40cf_a4a3_ccabea410e43_ff141_ctl00_ctl00_UserField(); return false;" title="Browse">
<img alt="Browse" src="/_layouts/15/images/addressbook.gif" title="Browse">
</a>
so my question if i can fire the script only when the user click on <a> that have an <imag> inside it where the imag src = addressbook.gif , instead of keeps firing the script every 2 seconds??
$('a img').on('click', callScriptForImage);
....
// it is executed every time, but will call function adjustPeoplePicker()
// only if src attribute includes addressbook.gif, as you asked
function callScriptForImage(e){
var src = $(this).attr('src');
// read image src attribute
if( /addressbook\.gif/.test(src)){
// if src attribute includes addressbook.gif, call function
adjustPeoplePicker();
}
}
You could also listen for clicks on image that have that src attribute, with:
$('a img[src$="addressbook.gif"]').on('click', adjustPeoplePicker);
This way it is a lot cleaner.
<html>
<head>
<script>
function setClick(){
var tL = document.querySelectorAll("img[src*='addressbook.gif']"); //Getting all images which src contains addressbook.gif
for(var i=0, j=tL.length;i<j; i++){
//Just to visualize
tL[i].style.outline = '1px solid red';
//We actually click on the parent (a) and not the img so we set the click on the a tag
//The other tags will keep your normal onclick settings.
tL[i].parentNode.onclick = function(){
//Put your special script for those cases.
//adjustPeoplePicker() //Some version of this.
return false
}
}
}
</script>
</head>
<body onload = 'setClick()'>
<a href = 'https://www.google.com'><img alt = 'Browse' src = 'https://www.google.com/images/srpr/logo11w.png' /></a>
<a href = 'https://www.google.com'><img alt = 'Browse' src = 'https://www.google.com/images/srpr/logo11w.png?test=addressbook.gif' /></a>
<a href = 'https://www.google.com'><img alt = 'Browse' src = 'https://www.google.com/images/srpr/logo11w.png' /></a>
</body>
</html>
https://jsfiddle.net/7u3m2cng/1/
I am assuming you're asking to check to see whether the <img> src = addressbook.gif and NOT the href of <a>?
If that is the case, this should work for you:
$('a img').on('click', function () {
//Check to see if if the href matches addressbook.gif
var src = $(this).attr('src');
var regex = /addressbook\.gif/i;
if (regex.test(src)) {
// Execute your code here.
} else {
//Put anything else you want here
}
});
Hope this helps!
JRad The Bad

Javascript replacing image source

I am trying to change the contents of the src tag within a web page (without changing the HTML/naming structure)
My code looks something like this at the moment:
....
<div class="main">
<button>
<img src="image/placeHolder.png"/>
<div>the nothing</div>
</button>
</div>
....
I need to change the src of this img tag
My javascript looks like this at the moment
....
<script type="text/javascript">
function changeSource() {
var image = document.querySelectorAll("img");
var source = image.getAttribute("src").replace("placeHolder.png", "01.png");
image.setAttribute("src", source);
}
changeSource();
</script>
....
I have no idea why it isn't working but I'm hoping someone out there does :D
Change your function to:
function changeSource() {
var image = document.querySelectorAll("img")[0];
var source = image.src = image.src.replace("placeholder.png","01.png");
}
changeSource();
querySelectorAll returns an array. I took the first one by doing [0].
But you should use document.getElementById('id of img here') to target a specific <img>
If you want to target all <img> that has placeholder.png.
function changeSourceAll() {
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
if (images[i].src.indexOf('placeholder.png') !== -1) {
images[i].src = images[i].src.replace("placeholder.png", "01.png");
}
}
}
changeSourceAll();
function changeSource() {
var img = document.getElementsByTagName('img')[0];
img.setAttribute('src', img.getAttribute('src').replace("placeHolder.png", "image.png"));
}

Javascript onMouseover to swap images

I have some code that makes an image larger when moused over:
<script>
function bigImg(x)
{
x.style.height="70px";
x.style.width="237px";
}
function normalImg(x)
{
x.style.height="56px";
x.style.width="218px";
}
</script>
and I call those functions with:
<a><img border="0" src="category_icons/addorder.png" onmouseover="bigImg(this)" onmouseout="normalImg(this)"></a>
But what I would really like to do is make it so the bigIMG(x) function also changes the image. I'm not extremely familiar with javascript and was wondering if someone knew what I can code in, to swap the image. The image name is addorder2.png. I've tried using this.src="addorder2.png"; but that is not working.
This will do. Change the image src into "addorder2.png".
<script>
function bigImg(x)
{
x.style.height="70px";
x.style.width="237px";
x.src = "addorder2.png";
}
function normalImg(x)
{
x.style.height="56px";
x.style.width="218px";
x.src = " addorder.png";
}
</script>
My 2 cents:
LIVE DEMONSTRATION
Don't use inline JS, rather you can set a data.* attribute
and an object literal that will contain your desired changes
and read it with JS:
<img class="zoom" src="img.jpg" data-enlarge='{"src":"img2.jpg", "zoom":"1.2"}'>
As you can see above we'll target with JS every element with class "zoom"
function enlarge(){
var el = this,
src = el.src,
data = JSON.parse(el.dataset.enlarge);
el.src = data.src;
el.style.transition = "0.3s";
el.style.transform = "scale("+data.zoom+")";
el.addEventListener('mouseleave', function(){
el.src = src;
el.style.transform = "scale(1)";
},false);
}
var $ZOOM = document.querySelectorAll('.zoom');
for(var i=0; i<$ZOOM.length; i++){
$ZOOM[i].addEventListener('mouseenter', enlarge, false);
}
With Javascript you can edit the src attribute of the img.
Javascript:
function bigImg()
{
document.getElementById("myImg").src="addorder2.gif";
}
HTML:
<!DOCTYPE html>
<html>
<body>
<img id="myImg" onmouseover="bigImg()" src="addorder.png">
</body>
</html>
I recommend checking out w3schools to learn more about image document manipulation and of course specifically getting and setting the image src element
Just change x.src property according to function:
function bigImg(x)
{
x.style.height="70px";
x.style.width="237px";
x.src = "category_icons/addorder2.png";
}
function normalImg(x)
{
x.style.height="56px";
x.style.width="218px";
x.src = "category_icons/addorder.png";
}

Programmatically change the src of an img tag

How can I change the src attribute of an img tag using javascript?
<img src="../template/edit.png" name="edit-save" alt="Edit" />
at first I have a default src which is "../template/edit.png" and I wanted to change it with "../template/save.png" onclick.
UPDATED:
here's my html onclick:
<img src="../template/edit.png" id="edit-save" alt="Edit" />
and my JS
function edit()
{
var inputs = document.myform;
for(var i = 0; i < inputs.length; i++) {
inputs[i].disabled = false;
}
}
I've tried inserting this inside the edit(), it works but need to click the image twice
var edit_save = document.getElementById("edit-save");
edit_save.onclick = function(){
this.src = "../template/save.png";
}
Give your img tag an id, then you can
document.getElementById("imageid").src="../template/save.png";
You can use both jquery and javascript method:
if you have two images for example:
<img class="image1" src="image1.jpg" alt="image">
<img class="image2" src="image2.jpg" alt="image">
1)Jquery Method->
$(".image2").attr("src","image1.jpg");
2)Javascript Method->
var image = document.getElementsByClassName("image2");
image.src = "image1.jpg"
For this type of issue jquery is the simple one to use.
if you use the JQuery library use this instruction:
$("#imageID").attr('src', 'srcImage.jpg');
its ok now
function edit()
{
var inputs = document.myform;
for(var i = 0; i < inputs.length; i++) {
inputs[i].disabled = false;
}
var edit_save = document.getElementById("edit-save");
edit_save.src = "../template/save.png";
}
Give your image an id. Then you can do this in your javascript.
document.getElementById("blaah").src="blaah";
You can use this syntax to change the value of any attribute of any element.
<img src="../template/edit.png" name="edit-save" onclick="this.src = '../template/save.png'" />
With the snippet you provided (and without making assumptions about the parents of the element) you could get a reference to the image with
document.querySelector('img[name="edit-save"]');
and change the src with
document.querySelector('img[name="edit-save"]').src = "..."
so you could achieve the desired effect with
var img = document.querySelector('img[name="edit-save"]');
img.onclick = function() {
this.src = "..." // this is the reference to the image itself
};
otherwise, as other suggested, if you're in control of the code, it's better to assign an id to the image a get a reference with getElementById (since it's the fastest method to retrieve an element)
In this case, as you want to change the src of the first value of your element, you have no need to build up a function. You can change this right in the element:
<a href='#' onclick='this.firstChild.src="../template/save.png"')'>
<img src="../template/edit.png" id="edit-save"/>
</a>
You have several ways to do this. You can also create a function to automatize the process:
function changeSrc(p, t) { /* where p: Parent, t: ToSource */
p.firstChild.src = t
}
Then you can:
<a href='#' onclick='changeSrc(this, "../template/save.png");'>
<img src="../template/edit.png" id="edit-save"/>
</a>
Maybe because you have a tag like a parent of the tag.
That why you have to click two time the images.
For me the solution is this:
http://www.w3schools.com/js/tryit.asp?filename=tryjs_intro_lightbulb

Categories