Swap images with a list of HTML links with JavaScript - javascript

I am trying to swap images using JavaScript. I have a main content area the loads one image. I have a sidebar with a list of links and I want to use JavaScript to change the image with each link. here is my code so far:
<html>
<head>
<title>Rat Dog Inc. ~ Services</title>
<script type="text/javascript">
var myImg;
var myImage= [];
myImage[0] = "../images/rd_surf_large.jpg";
myImage[1] = "../images/laundry.png";
myImage[2] = "../images/tug-o-war.png";
myImage[3] = "../images/cuddlepuppy.png";
myImage[4] = "../images/rd-howling.mp4";
function displayImg(){
document.getElementById('myImage[]');
}
</script>
</head>
<body>
<div id="main">
<img src="../images/rd_surf_large.png" alt="Rat Dog Inc." id="myImg"/>
</div>
<div id="sidebar">
<h2>Rat Dog Inc. Most Popular Services</h2>
<ul>
<li>Surfing Lessons <span style="font-size: 12px">(img)</span></li>
<li>Laundry Folding <span style="font-size: 12px">(img)</span></li>
<li>Tug-O-War Arm Workouts <span style="font-size: 12px">(img)</span></li>
<li>Cuddling <span style="font-size: 12px">(img)</span></li>
<li>Howling Lessons <span style="font-size: 12px">(video)</span></li>
</ul>
</div>

Ok. So here's the deal.
When you put your image on your page , like this:
<img src="image1.jpg" id="myImage">
And we assign the I'd 'myImage' to it....if we want to change the image via a link (I prefare a button), we use javascript in a way to manipulate it.
You simply use this method known as :
document.getElementById()
Which finds an element in our page by its I'd.
So if we put this button on our page:
<button onclick="changeImage()">Change The Image</button>
And put this script (which has the changeImage() function) :
<script>
function changeImage(){
var myImage = document.getElementById("myImage");
//then we change the src of the image
myImage.src="image2.jpg"
}
</script>
Our image will change of we click the button.
For reference , please visit http://www.htmldog.com/guides/javascript/intermediate/thedom
Thank you

You can use document.getElementById("image").src="image.png"; to change the src tag of an element.
Although for what you are doing, I reccomend you take a look at jQuery

please try and use this method of getElementById
For example:
<img id="image" src="image1.jpg">
<button onclick="changeToImage2('image')">Image 2</button>
<script>
function changeToImage(id) {
var myImage = document.getElementById(id);
myImage.src = "image2.jpg";
}
// then create other buttons and other functions to change the image.
</script>

Your javascript is incorrect. I'm not quite sure you understand how it works.
First of all, your function doesn't accept any parameters, and yet you're providing it with one. It will just ignore this because it doesn't know what to do with it.
Next, your document.getElementById in your displayImg() has the wrong input. Right now it's literally looking for an element with the ID "myImage[]"... of which there are none.
Also, you have a variable you never use (myImg). You should probably get rid of it.
Again, I'm getting the sense that you don't really know javascript that well or don't get the theory behind it. If you need help, w3schools has some great tutorials.

Related

retrieve contents of div and make image src

Is there a way to fetch the content of a div and place that ocntent in the 'src' parameter of an image? I'm working on a project that uses json to load translation files, and tehrefore I can't load an image directly, but figured I could at least load the image name.
So:
<div id="flag-name" style="hidden">en-flag.jpg</div>
<img src="DIV CONTENTS HERE">
Ideas appreciated! (Am also using jquery so open to that as well)
The button demonstrates that ablility. Use the button's onclick code wherever you need.
<div id="flag-name" style="hidden">en-flag.jpg</div>
<img id="myImage" />
<button onclick="document.getElementById('myImage').src=document.getElementById('flag-name').innerText">Change</button>
You can simply do it in jQuery by getting the text of the div and then setting the source of image like this:
var source = $("#flag-name").text();
console.log("before - " + $("#image").attr("src"));
$("#image").attr("src",source);
console.log("after - " + $("#image").attr("src"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="flag-name" style="hidden">en-flag.jpg</div>
<img id="image" src="DIV CONTENTS HERE">
You need an event to start the jQuery/javascript -- so I added a button. Also, you will find it easier to target specific DIV and IMG tags if you give them IDs or classes.
$('button').click(function(){
var mySrc = $('#flag-name').text();
$('img').attr('src', mySrc);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="flag-name" style="hidden">http://placeimg.com/300/200/animals</div>
<img src="DIV CONTENTS HERE">
<button>Go</button>

Capturing the text of the closest span element with a specific class

I'm trying to fetch the text of a span that has a given class -> closest to the click via Google Tag Manager. Is it possible via plain JS or JQuery?
The code looks like this:
<a class="contenttile" href="/mypage" style="height: 193px;">
<div class="imageContainer" style="height: 97px;">
<img src="http://http:someadress.com/foto.jpg" class="blurr" alt="">
</div>
<div class="textContainer">
<span class="text3">My text</span>
<br>
</div>
</a>
What I want to return via a function is My text.
I was trying different snippets found here, but since im a JS lame I couldn't adjust it to work properly.
For example this one:
function(){
var ec = {{Click Element}};
var x = $(ec).closest('span');
return x.innerText;
}
since you are using jQuery
return ec.find('.text3').text();
In GTM, your click may register two events: gtm.click and gtm.linkClick. Depending on which one your tag is set to fire on (ie. you can set it to fire on all clicks or just links), then you could use either of the following:
If using just links, then $(ce).find('.textContainer').find('span').text()
If using all clicks, then $(ce).closest('span').text()

Google Tag Manager - CSS selector challenge

I am trying to get the URL of a link in the source code. The challenge is that the URL is hidden behind a image, and thus only letting me fetch the image-url.
I've been trying to figure a way to solve this issue by using the new CSS selector in the trigger system and also made a DOM variable that should get the URL when the image is clicked. There can also be multiple downloads.
Here is an example of what I am trying to achieve:
<div>
<div class="download">
<a href="example.com/The-URL-I-Want-to-get-if-top-image-is-clicked.pdf" target="_blank">
<img src="some-download-image.png"/></a>
<div class="download">
<a href="example.com/Another-URL-I-Want-to-get-if-middle-image-is-clicked.pdf" target="_blank">
<img src="some-download-image.png"/></a>
<div class="download">
<a href="example.com/Last-URL-I-Want-to-get-if-bottom-image-is-clicked.pdf" target="_blank">
<img src="some-download-image.png"/></a>
</div>
</div>
There are much code above and below this snippet, but with the selector it should be fairly easy to get the information I want. Only that I don't.
If anyone have met this wall and solved it, I really would like to know how. :)
This is one possible solution. So as I understand it, you would like to grab the anchor element's href attribute when you click the "download" image.
A Custom Javascript variable would need to be created so that you can manipulate the click element object:
function(){
var ec = {{Click Element}};
var href = $(ec).closest('a').attr('href');
return href;
}
So you will need to do your due diligence and add in your error checking and stuff, but basically this should return to you the href, and then you will need to parse the string to extract the portion that you need.

how to convert an html script into a .js file script

would like to place the script into a .js file that opens already with
$(document).ready(function() {
});
I have tried but it feel slike because im putting the onMouse over command into the html I don't think it will be possible?
<head>
<style>
div > p {
cursor: pointer;
}
</style>
<script>
var monkeySrc = "http://icons.iconarchive.com/icons/martin-berube/animal/256/monkey-icon.png";
var lionSrc = "http://icons.iconarchive.com/icons/martin-berube/animal/256/lion-icon.png";
var treeSrc = "http://totaltreeworks.co.nz/wp-content/uploads/2011/02/Tree-256x256.png";
var falconSrc = "http://icons.iconarchive.com/icons/jonathan-rey/star-wars-vehicles/256/Millenium-Falcon-01-icon.png";
function changeImage(src){
document.getElementById("myImage").src = src;
}
</script>
</head>
<body>
<div class="images">
<img id="myImage" width="256" height="256">
</div>
<div>
<p onmouseover="changeImage(monkeySrc)">Monkey are funny!</p>
</div>
<div>
<p onmouseover="changeImage(lionSrc)">Lions are cool!</p>
</div>
<div>
<p onmouseover="changeImage(treeSrc)">Trees are green!</p>
</div>
<div>
<p onmouseover="changeImage(falconSrc)">Falcons are fast!<p>
</div>
</body>
</html>
If you were to take your existing JavaScript and place it in an external file, it would work just fine. It would work because all of your variables and your function would be in the global scope.
Going one step further you'll want to move those onmouseover event handlers into the JavaScript itself.
Given a small change to your current HTML and assuming jQuery you could do something like the following:
<p data-kind="monkey">Monkey are funny!</p>
then
var urlMap = {
monkey : 'http://icons.iconarchive.com/icons/martin-berube/animal/256/monkey-icon.png'
...
};
$('p').on('mouseover', function () {
var kind = $(this).data('kind');
var url = urlMap[kind];
changeImage(url);
});
which you would then be able to wrap in the $(document).ready, the shorthand for which is just $(function () { /* The code from above here */ });
You would need to bind the event handlers programmatically from within the .js file. jQuery would make this very simple and allow you to use arbitrary CSS selectors, but you can do the same in pure JS using e.g. document.getElementById and document.addEventListener.
You can bind the function to the event using Javascript addEventListner
1- Add id attribute to each of your paragraphs tags
<p id="p1"> .....</p>
2- Grab a variable that points to each of those
var p1 = document.getElementById('p1');
3- add event listner
p1.addEventListener("mouseover", changeImage(monkeySrc));
If you put your javascript code in another file and replace <script>...</script> with <script src="javascriptcodefilename.js"></script> in your HTML file, it still works as intended.
Example: http://codepen.io/anon/pen/waLqxz
It might be cleaner to add all of your urls to an array where the key is the name of the link, so you would have something like urls['lionSrc'] = "www.xyz.com";...
then in your changeImage function you would do document.getElementById("myImage").src = url[src];
this way you could even check to see if the image exists already, and if not, show an "image not found" icon.

Cloning JS generated DIV to non generated DIV

I have a bit of what seems like a complicated issue(to me at least)
I've got an external javascript file generating html content for me. It's for tweets. It gives each one a individual ID, which I can see in the browser but of which is obviously not in my index.html.
The JS generates something like this in the browser http://i.imgur.com/8yxLYBa.png
Heres the generated div
<div class="twitter-article" id="tw1"><div class="twitter-pic"><img src="https://pbs.twimg.com/profile_images/461533054800900097/5h4n1K31_normal.jpeg" twitter-feed-icon.png"="" width="42" height="42" alt="twitter icon"></div><div class="twitter-text"><p><span class="tweetprofilelink"><strong>JGD</strong><br> #jdrawsthings</span></p><b><span class="tweet-time"></span></b><d>2h, Glasgow. Favorites: 0 Retweets: 0</d><br><c>Literally desperate and just need to secure a nice room in a nice flat close to DJCAD so I can move in June 20th</c></div><div class="favourite-item" id="fav1"><button class="favouriteButton" id="favBut1"></button></div><div id="twitter-actions" style="opacity: 0; margin-top: -20px; display: none;"><div class="intent" id="intent-reply"></div><div class="intent" id="intent-retweet"></div><div class="intent" id="intent-fave"></div></div></div>
Each one has a button assigned to it, which each also have individual IDs.
I'm wanting to use the clone function to copy across the contents of say, '#tw1' into '#faveDiv'. #faveDiv been a div on my index.html page.
<div id="favouriteStreamHolder">
<div id="favouriteStream" style="display: none;">
<div id="faveDiv"></div>
</div>
</div>
Here is the clone function I'm trying
$("input#favBut1").live( 'click', function(){
$('#faveDiv').html($('#tw1').html());
});
There's to much going on that relies on PHP that putting it into a simulator wouldn't achieve anything. Basically, that JS creates this. i.imgur.com/8yxLYBa.png A stream of 25 tweets of which the content is created in that js function having been pulled from a JSON file. I'm under the assumption that the .clone() function should copy all within the div and duplicate it into the div ive specified. At the moment. It's doing nothing, the div is just empty. Bit new to this, sorry. If theres anything else you need to know. Just say.
Any idea why this isn't working?
Try this (pattern)
html
<div id="favouriteStreamHolder">
<div id="favouriteStream">
<div id="faveDiv"></div>
<!--
duplicate `favBut1` in `feedHTML`,
substitute `id` `feed` for `favBut1`
-->
<input type="button" id="feed" value="click" />
</div>
</div>
js
$(function () {
// var feedHTML = `$.parseHTML(feedHTML)`
var feedHTML = $.parseHTML('<div class="twitter-article" id="tw1">..</div>');
$(document).on("click", "#feed", function (e) {
e.preventDefault();
$(e.target).siblings("#faveDiv").html($(feedHTML));
});
})
jsfiddle http://jsfiddle.net/guest271314/ReK9u/

Categories

Resources