Replace html elements from a list of elements - javascript

This may sound a dumb question. I have a set of images inside a page. And these images doesnt have an ID but a class. I want to get these elements by their class names and replace each of them with different content. How should I do that.

The following using vanilla JavaScript (no jQuery) and does:
Select images in your page which have a class assigned (in this example imageClass). The document.querySelectorAll() allows you to select DOM elements using CSS3 selectors.
Change "content" for each image (src link), so yo ucan show up different images.
Click the button in the example to change "content" for images.
(function() {
var changeContent = function() {
document.querySelectorAll('.imageClass').forEach(function(image) {
image.src = 'https://placeimg.com/340/280/people'
});
};
document.getElementById('btn').addEventListener('click', changeContent);
})();
<button id="btn" type="button">Change Images</button>
<img class="imageClass" src="https://placeimg.com/240/180/animals">
<img class="imageClass" src="https://placeimg.com/240/180/animals">
<img class="imageClass" src="https://placeimg.com/240/180/animals">
<img class="imageClass" src="https://placeimg.com/240/180/animals">

Related

jQuery function to open 2 connected, draggable images on click

I am new to programming and it should be easy, however I can't understand how to do it. I need create 2 images on one button click, one image is main, another is like close X button. They must be connected and draggable.
This is my function: Js Fiddle link
<input type="button" id="truck" class="truckbtn" value="ADD Truck" onclick="addtruck()">
<div id="masina">
<div id="closebutton"></div>
<div id="truckshow"></div>
</div>
<Script>
$(document).ready(function() {
$(".truckbtn").click(function() {
var truckshow = $('<img height="200" width="100" src="images/Truck1.png">');
var closebutton = $('<img height="50" width="50" src="images/closeimage2.png">');
$('div').prepend(truckshow + closebutton);
truckshow.draggable();
closebutton.draggable();
});
});
</Script>
Here I have a sample code (JS Fiddle) using draggable() of Jquery UI for dragging components inside DOM.
My buttons style are from Bootstrap, you can also write custom CSS although I used a framework for saving time.
EDITS
Image is dynamically added on button click.
You can change image dynamically by changing src of <img/> tag using jquery.
let <img id="myImage"/> then you can set src by $("#myImage").attr("src","your link here");.
FIDDLE

Making an image change from one to the next in 2 seperate divs

I am trying to create two divs with a rotating image in on my webpage, these change to another image after a certain amount of seconds and there are 3 images to display. At the moment I am just trying to get the mechanics of this working using the code below, but although its simple I can not get it working. the code is the same as what I have used before however this time it does not want to work. I did it last, years agao, and I have completely forgotten how and research has not helped.
My code is below. In case this problem is site specific I have also included a livelink HERE which I shall remove once the question is answered. THE TWO DIVS ARE THE RED AND YELLOW BOXES.
JAVASCRIPT
var rotators = [
{ id: 'advert1', images: ['http://www.w3schools.com/html/html5.gif', 'http://www.w3schools.com/html/pic_mountain.jpg', 'http://www.w3schools.com/html/pic_graph.png'], selectedIndex: 0 },
{ id: 'advert2', images: ['http://www.w3schools.com/css/klematis_big.jpg', 'http://www.w3schools.com/css/klematis2_big.jpg', 'http://www.w3schools.com/css/klematis3_big.jpg'], selectedIndex: 0 }
];
var updateImages = function() {
for (var i=0; i < rotators.length; i++) {
var rotator = rotators[i];
rotator.selectedIndex++;
if (rotator.selectedIndex >= rotator.images.length) {
rotator.selectedIndex = 0;
}
document.getElementById(rotator.id).src = rotator.images[rotator.selectedIndex];
}
};
var timer = setInterval(updateImages, 1000);
</script>
HTML
<div id="main">
<div id="advert1"></div>
<div id="advert2"></div>
</div>
You are trying to set the div src. you need to have an image (img) element inside each div and then to set the image src.
<div id="main">
<div>
<img id="advert1" alt="" src.../>
</div>
<div>
<img id="advert2" alt="" src.../>
</div>
</div>
Another option will be to set the div background image using the style property or class property (both using CSS sets with JavaScript).
The javascript is executed where you write, if you write before element then the element does not exist.
You can attach code to onReady event of document or puts code after element.
Looking at your code in Google Chrome, I see the following error in the console :
Uncaught ReferenceError: $ is not defined | new.html:204
It seems like you forgot to include the jQuery in your html page.
You can get it from a CDN on the following page: http://code.jquery.com/
Another problem is that you're trying to update an img but your DOM element is a div.
You should replace the following code:
<div id="main">
<div id="advert1"></div>
<div id="advert2"></div>
</div>
With:
<div id="main">
<img src="" id="advert1" />
<img src="" id="advert2" />
</div>

change the opacity of another image inside of another div by hovering over another div image

Is this too complicated to achieve? Hopefully my question or title makes sense. Essentially I have two divs - one is and the other is . I have 12 images inside of each div that I thought I attached IDs to. I'm still much of a noob to web coding so perhaps I'm labeling them wrong. But here's my goal, whenever you hover over artwork1, the opacity of artwork1 and button1 should change simultaneously. And the effect needs to be achieved the other way as well (ie hover:button1 should change the opacity of artwork1). Below is my code to explain my case further:
<html>
<body>
<div id="buttons">
<img src="..." class="spaced"(to spaced the buttons)>
<img src="..." class="spaced">
<div id="artwork">
<img src="..." class="mainbuttons & greydout"
<img src="..." class="mainbuttons & greydout">
The 'mainbuttons' class is for spacing between the 12 images. And the greydout class is to alter the hover effect already in place - going from opacity 0.3 to 1.
I've tried to research some javascript as I'm thinking that's the most proper solution. My javascript I've tried to use is as follows:
$(document).ready(function() {
$("#button1").mouseenter(function(){
$("#artwork1").addClass("opac_art");
});
$("#button1").mouseleave(function(){
$("#artwork1").removeClass("opac_art");
$("#artwork1").addClass("greydout")
});
});
One more thing to consider is that I have multiple scripts running for various functions:
1) a redirect script that will redirect mobile viewers to the mobile site;
2) a respond script that reformats the viewport to whatever the viewer's resolution browser size is set to.
I have the jQuery loaded up at the top of the document, but could there be conflict with the other scripts running on the html page?
I've even tried going the CSS route and I can barely get the divs to interact with each other. The closest I've come is when I hover in the button div, I can alter artwork 1, but not as specific as I'm aiming for. I hope all this makes sense, and thanks in advance for reading all this and trying to help me through this huge roadblock to getting my site up.
Try something like this.
Add a class to your buttons (galleryButtons) and to your images in the other div.
First of you do not really need the wrapping with the a tag
Add classes to your button elements and artwork.
<div id="buttons">
<img id="gbutton1" class="galleryButtons" src="button.png" />
<img id="gbutton2" class="galleryButtons" src="button.png" />
<div id="artwork">
<img id="artwork1" class="artworkImage" src="art1.jpg" />
<img id="artwork2" class="artworkImage" src="art2.jpg" />
$(document).ready(function () {
var intID;
$(".galleryButtons").hover(function (e) {
console.log(e.target.id);
var id = e.target.id;
intID = id.replace(/^\D+/g, '');
$("#artwork" + intID).addClass("opac_art");
}, function () {
$("#artwork" + intID).removeClass("opac_art").addClass("greydout");
});
$(".artworkImage").hover(function (e) {
var id = e.target.id;
intID = id.replace(/^\D+/g, '');
$("#gbutton" + intID).addClass("opac_art");
}, function () {
$("#gbutton" + intID).removeClass("opac_art").addClass("greydout");
});
});
All for you in a fiddle: http://jsfiddle.net/djwave28/et6tD/4/
It can be made simpler with selecting smarter, but I wanted you to see the relation in the element better. When you hover over an element, the element that causes the event is send to the function. This event contains information. Like e.target.id will hold the id of that element.
http://www.w3schools.com/jsref/dom_obj_event.asp
From what I'm understanding of your question, you could do something like this:
$(document).ready(function()
{
$("#one").hover(function()
{
// Changes the opacity of the first image
// as well as the corresponding link from
// 1 to 0.3.
$("#artone").css({ "opacity": "0.3" });
$(this).css({ "opacity": "0.3" });
});
$("#two").hover(function()
{
$("#arttwo").css({ "opacity": "0.3" });
$(this).css({ "opacity": "0.3" });
});
});
And the HTML would look something like this:
<div id="links">
Link one
Link two
</div>
<div id="artwork">
<img src="" id="artone" class="spaced">
<img src="" id="arttwo" class="spaced">
</div>
Couple extra things -
Make sure you actually link jQuery into your page's header, I didn't see it above:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
That's from Google's CDN, but you can do it locally, of course.
<img src="#" class="mainbuttons & greydout">
When listing classes for an element, you don't add an ampersand (&), you just leave them with a space in between.
<img src="#" class="mainbuttons greydout">

Javascript functions Swapping Images

I am supposed to
Write and use a JavaScript function to insert content into an HTML element:
• Create a function named swapOut that includes the statement: document.imageFlip.src="name of the first image".
• Create a function named swapBack that includes the statement: document.imageFlip.src="name of the second image".
• Insert a div tag with an id and name of myImage.
• Inside the div container, insert an image tag with an id and name of imageFlip. Initialize the image tag to display the first image. Set the height and width attributes. Set the alt and title attributes to "Swappable image".
alt="Swappable image" title="Swappable image" height="" width=""
• Inside the image tag, add onmouseover="swapOut()" and onmouseout= "swapBack()". These define events that the image element recognizes. The first calls your swapOut function when you move the mouse over the image; the second calls your swapBack function when you move the mouse off the image.
So far i have done this.
in my .js form i have
function swapOut() {
document.imageFlip.src = "firstImage"
}
function swapBack() {
document.imageFlip.src = "secondImage"
}
and in my .htm form I have
<div id="myImage" name="myImage">
<img src="firstImage.png" alt="Swappable image" title="Swappable image" id="imageFlip"
name="imageFlip" onmouseout="swapBack()" onmouseover="swapOut()" height="200" width="200"/>
</div>
I need the images to swap but I get the first image however when i hover over it i only get a box with no picture
Make sure what your assigning to your 'src' attribute has the full image path and extension.
For your case it would be
document.imageFlip.src = "firstImage.png"
// or
document.imageFlip.src = "secondImage.png"
Also you can use
document.getElementById('imageFlip').src = "firstImage.png"
If you don't want to use the name attribute everywhere, this is the common way to do this type of thing, and (I could be wrong on this) but I think the name attribute is deprecated in HTML5.
you miss the extension of your image.
<img src="firstImage.png" alt="Swappable image" title="Swappable image" onMouseOver="this.src='secondImage.png'" onMouseOut="this.src='firstImage.png'" height="200" width="200"/>

How to append HTML to images using JQuery?

I am using Galleria and I need to wrap my images that Galleria puts into a slide with a link.
I was going to use this methodology: Give the <img> a bogus title= value and then append a <a> tag around the <img>, drawing the link I need from the title= tag.
This is the code I've got so far.
$("img#gallery").this.title.appendTo("img#gallery") { });
I'm trying to get the script to loop through all of the images and append the html.
I also don't know if I should be using .appendTo or .before and .after
That approach will work. You're looking for the wrap function:
var title = $('#test').attr('title');
$('#test').wrap('<a href="'+title+'" />');
This $.each will let you iterate through a series:
<img src="" class="test" alt="test" title="http://www.google.com" />
<img src="" class="test" alt="test" title="http://www.yahoo.com" />
$.each($(".test"), function() {
var title = $(this).attr('title');
$(this).wrap('<a href="'+title+'" />');
});
You could just listen for a click on the entire thing and then figure out if an image was clicked and if so which image and then change the location object.
Use $.each to iterate through all the images you want to wrap and then use
$('img#gallery').wrap('<a href='whatever'>)
to wrap it. It will automatically close the A tag.

Categories

Resources