I am trying to figure out a way to insert the first image of a jquery gallery once it's loaded basically.
I've searched everywhere and can't seem to find anything. I have pasted the code that works so far below. I think I have to put something like:
$(function() {
$(".image").click(function() {
var image = $(this).attr("rel");
var title = $(this).attr("alt");
var description = $(this).attr("content");
$('#gallery').hide();
$('#gallery').fadeIn('slow');
$('#image').html('<img src="' + image + '"/>');
return false;
});
});
use .append
example
$(".image").click(function() {
var img = $('<img/>');
img.attr("src", $(this).attr("rel") );
var title = $(this).attr("alt");
var description = $(this).attr("content");
$("#gallery").append( img );
$('#gallery').fadeIn('slow');
return false;
});
This will also append other images once their respective links been clicked.
Related
I'm a noob working my way to learn JavaScript on my own and using some resources but want to probe things on my own hence trying this thing but it's not working for some reason. Help is appreciated.
The object is to clarify some blurred images by swapping the source. The images are called zero.jpg/zeroblur.jpg, one.jpg/oneblur.jpg and so on... The page loads with blurred image sources until clicked on. I want to write code so that it goes back to original blurred source image after 5 secs.
P.S.: The code in comments is what I've tried to write on my own.
window.onload = init;
function init() {
var blurryPic = document.getElementsByTagName("img");
for (var i = 0; i < blurryPic.length; i++) {
blurryPic[i].onclick = clarify;
// setTimeout(resetPic, 5000);
}
}
function clarify(eventObj) {
var pic = eventObj.target;
var id = pic.id;
id = "images/" + id + ".jpg";
pic.src = id;
}
// function resetPic(eventObj) {
// var pic = eventObj.target;
// var id = pic.id;
// id = "images/" + id + "blur.jpg";
// pic.src = id;
// }
It's better with CSS: your image stays the same and you only toggle a class, the class making your image blur.
document.getElementById("clickImg").addEventListener("click", function() {
this.classList.toggle("blurImg")
})
.blurImg {
-webkit-filter: blur(5px); /* Safari 6.0 - 9.0 */
filter: blur(5px);
}
<img src="https://www.muralsticker.com/23751-thickbox/autocollants-en-vinyle-pour-enfants-spongebob-squarepants.jpg" id="clickImg">
If what you want is really to be able to reset the original image, I think it's better to stock it in a specific attribute, like this:
document.getElementById("reset").addEventListener("click", function() {
document.getElementById("clickImg").src = document.getElementById("clickImg").getAttribute('origSrc')
})
var imgs = [
'https://vignette.wikia.nocookie.net/spongebob/images/d/d7/SpongeBob_stock_art.png/revision/latest?cb=20190921125147',
'https://static.vecteezy.com/system/resources/previews/000/072/351/non_2x/spongebob-squarepants-vector.jpg',
'https://upload.wikimedia.org/wikipedia/en/c/c7/BattleForBikiniBottom.jpg'
]
document.getElementById("random").addEventListener("click", function() {
document.getElementById("clickImg").src = imgs[Math.floor(Math.random() * 3)]
})
<input type="button" value="RESET" id="reset" />
<input type="button" value="RANDOM" id="random" /><br/>
<img src="https://www.muralsticker.com/23751-thickbox/autocollants-en-vinyle-pour-enfants-spongebob-squarepants.jpg" origSrc="https://www.muralsticker.com/23751-thickbox/autocollants-en-vinyle-pour-enfants-spongebob-squarepants.jpg" id="clickImg">
I used an if statement for this to check if the first loaded image file was present or not. Then use the attribute src for the file. Here's an example.
#javascript
function magicChanger(){
var myImage = document.getElementById("emailImage")
if (myImage.getAttribute("src") == "first loaded image"){
myImage.setAttribute("src", "second image")
}
else{
myImage.setAttribute("src", "first loaded image")
}
}
#html element
<button id = "emailButton" onclick="magicChanger()">
<img id="emailImage" src="{% static 'GoEnigmaPics/emailIcon.png' %}" alt="email">
</button>
Thanks for all the answers! I wanted to get it done in JS only so CSS wouldn't work. Appreciate the answers and will definitely incorporate in future projects!
P. S. This is what got it done in the end.
window.onload = init;
function init() {
var blurryPics = document.getElementsByTagName("img");
for (var i = 0; i < blurryPics.length; i++) {
blurryPics[i].onclick = clarify;
}
function clarify(eventObj) {
var pic = eventObj.target;
var id = pic.id;
id = "images/" + id + ".jpg";
pic.src = id;
setTimeout(reBlur, 3000, pic);
}
function reBlur(eventObj) {
var pic = eventObj.target;
var id = pic.id;
id = "images/" + id + "blur.jpg";
pic.src = id;
}
Please try this code,To Is there a way to switch images src back to original after on.click src change event?
It switches back because by default, when you click a link, it follows the link and loads the page. In your case, you don't want that. You can prevent it either by doing e.preventDefault();
$(function() {
$('.menulink').click(function(){
$("#bg").attr('src',"img/picture1.jpg");
return false;
});
});
I hope this code will be useful.
Thank You.
I've looked at numerous other answers regarding this but haven't found a solution that has worked. I'm using a PHP page that contains some HTML code, with Javascript working some functions. Ideally I would select an image on the page, the image will become colored green as it is selected. I would then like to deselect the image and have it return to the original state. I can only get half-way there however. What am I missing? Is it something with post back?
Here's some code examples:
The HTML:<div onclick="changeImage(1)" id="toolDiv1"><img id="imgCh1" src="/images/Tooling/1.png"></div>
The Javascript function:
function changeImage(var i){
var img = document.getElementById("imgCh" + i + ".png");
if (img.src === "images/Tooling/" + i + ".png"){
img.src = "images/Tooling/" + i + "c.png";
}
else
{
img.src = "images/Tooling/" + i + ".png";
}
}`
The "1c.png" image is the one that is selected and should replace "1.png". There are multiple divs on this page that hold multiple images, which are named 2/2c, 3/3c, which is why the var i is included. Any insight? Thanks in advance.
You could do it something like this, it would also allow for different file names.
<img class="selectable" src="/images/Tooling/1.png"
data-original-source="/images/Tooling/1.png"
data-selected-source="/images/Tooling/1c.png">
<img class="selectable" src="/images/Tooling/2.png"
data-original-source="/images/Tooling/2.png"
data-selected-source="/images/Tooling/2c.png">
var images = document.getElementsByClassName('selectable');
for (var image of images) {
image.addEventListener('click', selectElementHandler);
}
function selectElementHandler(event) {
var image = event.target,
currentSrc = image.getAttribute('src'),
originalSrc = image.getAttribute('data-original-source'),
selectedSrc = image.getAttribute('data-selected-source'),
newSrc = currentSrc === originalSrc ? selectedSrc : originalSrc;
image.setAttribute('src', newSrc);
}
With comments:
// find all images with class "selectable"
var images = document.getElementsByClassName('selectable');
// add an event listener to each image that on click runs the "selectElementHandler" function
for (var image of images) {
image.addEventListener('click', selectElementHandler);
}
// the handler receives the event from the listener
function selectElementHandler(event) {
// the event contains lots of data, but we're only interested in which element was clicked (event.target)
var image = event.target,
currentSrc = image.getAttribute('src'),
originalSrc = image.getAttribute('data-original-source'),
selectedSrc = image.getAttribute('data-selected-source'),
// if the current src is the original one, set to selected
// if not we assume the current src is the selected one
// and we reset it to the original src
newSrc = currentSrc === originalSrc ? selectedSrc : originalSrc;
// actually set the new src for the image
image.setAttribute('src', newSrc);
}
Your problem is that javascript is returning the full path of the src (you can try alert(img.src); to verify this).
You could look up how to parse a file path to get the file name in javascript, if you want the most robust solution.
However, if you're sure that all your images will end in 'c.png', you could check for those last 5 characters, using a substring of the last 5 characters:
function changeImage(var i){
var img = document.getElementById("imgCh" + i);
if (img.src.substring(img.src.length - 5) === "c.png"){
img.src = "images/Tooling/" + i + ".png";
}
else
{
img.src = "images/Tooling/" + i + "c.png";
}
}
I've created a snippet to swap images between no underscore and '_1' in the source path when hovering and leaving the .hover()
Sometimes I see an issue whereby the next image I hover over get's the 'styled' image from the previous image i hovered over (this is inconsistent!) with '_1'?
I think it has to do with the speed at which you hover over the images.
I'm using $(this) to refer to the div the user is currently hovering over and maybe it's inconsistently storing the src for the img and referencing it too soon?
Please see below a video demonstrating my issue:
http://screencast.com/t/lJEDb5lyTXj5
PS: I don't have access to the source code - I am injecting this code onto the site, (So i can't manipulate the divs/images without JS)
<head>
<style>
.js div.result.product {
display: none;
}
</style>
<script>
$('html').addClass('js');
</script>
<script>
$( document ).ready(function() {
$('div.result.product').show();
});
</script>
</head>
<script>
console.log($('div.result-image').length);
// Function to set all images with _1 to no "_1".
$( "div.result-image > a > img" ).each(function() {
console.log('one image');
var styled = "_1";
var revertStyledOriginal = $(this).attr('src');
var preset = "?hei=245&qlt=85,1&wid=245&fmt=jpeg&resMode=bicub&op_sharpen=1";
// if the img is silo
var s = revertStyledOriginal;
// Only takes everything up until the "_"
unstyle = s.substring(0, s.indexOf('_'));
// add the preset back onto the src to make the img crisp
var unstyled = unstyle + preset;
// sets this instance of the image in the each loop to the "new link" with removed "_1"
$(this).attr('src', unstyled);
});
// Hover Function
$('div.result.product').hover(function myfunc() {
//Store 'this' as a reference to the current product image to be referred to when switching images
var selection = $(this);
$link = selection.find('img').attr('src');
$parsed = $link;
var styled = "_1";
var revertStyledOriginal = selection.find('img').attr('src');
var preset = "?hei=245&qlt=85,1&wid=245&fmt=jpeg&resMode=bicub&op_sharpen=1";
//if the img is silo
if(revertStyledOriginal.indexOf(styled) === -1 && ($link !== "http://www.kirklands.com/assets/HTML/MVS/AB_tests/NextPageButton/Next_Page_Buttons_Page_2.jpg"))
{
$preset = "?hei=245&qlt=85,1&wid=245&fmt=jpeg&resMode=bicub&op_sharpen=1";
//Need to remove preset to add _1 (then readd preset).
$removedPreset = $parsed.substring(0, $parsed.indexOf('?'));
var Unstyled = $removedPreset + $preset;
var Styled = $removedPreset + "_1" + $preset;
function checkImage(src) {
var img = new Image();
img.onload = function() {
// code to set the src on success
selection.find('img').attr('src', Styled)
//console.log('exists');
//console.log(revertStyledOriginal);
};
img.onerror = function() {
selection.find('img').attr('src', Unstyled)
console.log('doesnt exist');
//console.log();
};
img.src = src; // fires off loading of image
}
checkImage(Styled);
}
//if the img is styled
else {}
//$( this ).attr("src",);
},
//Function to reset the image on when you exit hover of img
function() {
$original = $(this).find('img').attr('src')
$removedPreset = $parsed.substring(0, $parsed.indexOf('?'));
$link = $removedPreset + $preset;
if ($original !== "http://www.kirklands.com/assets/HTML/MVS/AB_tests/NextPageButton/Next_Page_Buttons_Page_2.jpg") {
// set on hover image src to silo
$(this).find('img').attr('src', $link)
}
});
</script>
I have an XHR response that returns images. I have my function in order to show the images. I am combining JQuery and JS in the same code snippet. So far all is working well:
function resultat(o){
var leselements = o.query.results.bossresponse.images.results.result;
var output = '';
var no_items = leselements.length;
for(var i=0;i<no_items;i++){
var lien = leselements[i].url;
//place image urls in img src
output += "<img src='" + lien + "' class='imgs'>";
}
// Place images in div tag
document.getElementById('results').innerHTML = output;}
But I would like to allow users to click an image and then populate an input field ('#imageurl') with the clicked image src. Here is what I tried but it does not work.
$('.imgs img').click(function(){
$('#imageurl').val() = "";
var source = $(this).attr('src');
$('#imageurl').val() = source;
});
Any help will be greatly appreciated. TIA.
Using .val() in this way will just return the current value of #imageurl.
$('#imageurl').val()
.val is a function call that works as a getter and a setter.
To set the value, try this:
$('#imageurl').val(source);
$('#imageurl').val("");
// ...
$('#imageurl').val(source);
See the documentation.
Try this:
$('img.imgs').click(function(){
var src = $(this).attr('src');
$('#imageurl').val(src);
});
If the image will be rendered after the attachment of the event handler use this:
$('img.imgs').live('click', function(){
var src = $(this).attr('src');
$('#imageurl').val(src);
});
Thank you guys for your prompt answers. I tried all of them but they did not work for me. I then asked a friend and we finally found a way to make it work. Probably not the best or professional way but it works. Here is the solution if ever anyone needs it.
function resultat(o){
var leselements = o.query.results.bossresponse.images.results.result;
var output = '';
var no_items = leselements.length;
for(var i=0;i<no_items;i++){
var link = leselements[i].url;
//Place urls in image src and pass in 'link' parameter to the getsrc function
output += "<img src='" + link + "' onclick='getsrc(\""+link+"\")'>";
}
// Place images in div tag
document.getElementById('results').innerHTML = output;
}
function getsrc (link) {
//console.log($(this));
$('#imageurl').val("");
// var source = $(this).attr('src');
//place imageurl value by passing in the link parameter.
$('#imageurl').val(link);
}
I have a large number of images of the same class "linkImg" and I would like them to behave as links without adding tags.
What I'm tryng is something like this:
<script type="text/javascript">
$(function()
{
$('.linkImg').click( function( event )
{
var fileSrc = $(this).attr('src');
fileSrc = fileSrc.slice(fileSrc.lastIndexOf('/')+1,-4); // gets the image file name
var linkPath = '_img/largeImg/' + fileSrc + '.jpg';
var linkRel = 'relValue';
var linkTarget ='targetValue';
gotothelinl(linkPath, linkRel, linkTarget)// this is just a made-up function - it the part I don't know how to make work
})
} );
</script>
When it works it should behave like the tag was there with all attribute intact. I tried using location.href but I can't ad rel or target attributes to that.
thx in advance
David
To change the location of the page you'd do
location.href = "/newLocation.html"
This simulates a hyperlink (although I'm an ajax enthusiast!)
I think your are taking the problem for another angle... try this:
<script type="text/javascript">
$(function()
{
$('.linkImg').each( function()
{
var fileSrc = $(this).attr('src');
fileSrc = fileSrc.slice(fileSrc.lastIndexOf('/')+1,-4); // gets the image file name
var linkPath = '_img/largeImg/' + fileSrc + '.jpg';
var linkRel = 'relValue';
var linkTarget ='targetValue';
$(this).wrap('<a href="'+ linkPath +'" target="' + linkTarget + '" rel="'+ linkRel + '" />')
})
} );
</script>