Bootstrap Carousel not working after adding items dynamically with jQuery - javascript

I have Bootstrap Carousel as shown below
<div class="carousel slide multi-item-carousel" id="theCarousel3">
<div class="carousel-inner">
<div class="item active">
<div class="col-lg-4">
<img src='images/image1.jpg' id='img' class='img-responsive' width='250' height='300' />
</div>
</div>
<div class="item">
<div class="col-lg-4">
<img src='images/image2.jpg' id='img' class='img-responsive' width='250' height='300' />
</div>
</div>
<div class="item">
<div class="col-lg-4">
<img src='images/image3.jpg' id='img' class='img-responsive' width='250' height='300' />
</div>
</div>
</div>
<a class="left carousel-control" href="#theCarousel" data-slide="prev"></a>
<a class="right carousel-control" href="#theCarousel" data-slide="next"></a>
</div>
It works fine as it is but when I add images with jQuery by appending same html blocks as shown below it doesn't work anymore:
$('#myContent').append("<div class='carousel slide multi-item-carousel' id='theCarousel3'><div class='carousel-inner'>");
for(var x = 0; x < imageCount; x++) {
var imgElement = "<div class='item'><div class='col-lg-4'><img src='"
+ pictures[x].path + "' id='img" + x +
"' class='img-responsive' width='250' height='300' /></div></div>";
$('#myContent').append(imgElement);
if(x == 0) $('#theCarousel3 .item').addClass('active');
}
$('#myContent').append("</div><a class='left carousel-control' href='#theCarousel3' data-slide='prev'></a><a class='right carousel-control' href='#theCarousel3' data-slide='next'></a></div>");
I have even added the active class for the first item which seem to me a possible issue but still not working, what I see is images added one by one but not sliding. What could be the issue here, any help please? Thanks.

you need to add you images to the same DOM element as you other images.
instead of $('#myContent').append(imgElement); it should be
$('#theCarousel3 .carousel-inner').eq(0).append(imageElement);
You may be able to get rid of the eq(0) part, but I'm not sure if that will work since class selector is multiple.
the other option is to add the myContent id to your carousel-inner element
you also arent creating valid html the way you are trying to create the carousel
try this:
$(function() {
var imgElement,
pictures = [
'https://storage.googleapis.com/gweb-uniblog-publish-prod/static/blog/images/google-200x200.7714256da16f.png',
'https://lh3.googleusercontent.com/Rz-Ob1uRO2Xch40qHYgxpZitc3vZzxjeeSHVaNazn4dUny-AqGK0hLXUxhTpg4qgATP6VdlvZPYv_o0=s559-no',
'http://blog.suite-logique.fr/wp-content/uploads/2014/01/G7N0lnxM.jpeg',
'http://inspiratron.org/wp-content/uploads/2014/07/google-hummingbird.jpg'
]
wrapper = $('#myContent'),
carousel = $('<div/>', {
id: "theCarousel3",
"class": "carousel slide multi-item-carousel",
append: '<div class="carousel-inner"></div><a class="left carousel-control" href="#theCarousel3" data-slide="prev"></a><a class="right carousel-control" href="#theCarousel3" data-slide="next"></a>'
}),
carouselInner = carousel.find('.carousel-inner').eq(0);
wrapper.append(carousel);
carousel.carousel();
for (var i = 0; i < pictures.length; i++) {
imgElement = $('<div/>', {
"class": "item" + (i ? '' : ' active'),
append: $('<div/>', {
"class": 'col-lg-4',
append: $('<img/>', {
src: pictures[i],
id: 'img' + i,
"class": 'img-responsive',
height: 300
})
})
})
carouselInner.append(imgElement);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container-fluid">
<div id='myContent'></div>
</div>

Note: Frist div have 'item' and 'active' class, and all other div have only 'item' class then it will work otherwise it will not work.
<div class="item active">
<div class="col-lg-4">
<img src='images/image1.jpg' id='img' class='img-responsive' width='250' height='300' />
</div>
</div>
<div class="item">
<div class="col-lg-4">
<img src='images/image2.jpg' id='img' class='img-responsive' width='250' height='300' />
</div>
</div>
<div class="item">
<div class="col-lg-4">
<img src='images/image3.jpg' id='img' class='img-responsive' width='250' height='300' />
</div>
Its working for me, hopefully it will also work for you. Thank you!!!!!!!!

Related

Why is Bootstrap 4 carousel pause function not working when it's getting called from the event of an element inside of the carousel?

So I was trying to wrap my head around this issue, and I asked the question yesterday:
Carousel('pause') isn't working on mobile devices
I found the symptom so I'm asking a new question with a new focus.
The question title is not telling everything, because it would be too large:
This is only happening on phones, using mobile browsers, On desktop is totally fine.
Basically, if you have a Bootstrap 4 carousel, and you have any element that is inside of the div with the id of the carousel and you want to attach an event on that element (like a click) to pause the carousel, it wont work AT ALL, the slider keeps cycling.
I've tried click, mousedown, mouseup, I've tried setting the selector's click event on body, tried calling a click event on a selector that is outside to pause it, used parents, etc, and it wouldn't work.
Created a button that is right outside the carousel, attached a click event to it and it works.
I'm using the latest BS (4.4.1)
This is my code:
Blade file:
<div id='slider'>
<button class='pause-carousel' role='button'>Pause from outside</button>
<div id='sme-directory-gallery' class='carousel slide' data-ride='carousel'>
<button class='pause-carousel-2' role='button'>Pause from inside</button>
<div class='carousel-inner'>
#foreach($directoryInfo->videos as $index => $video)
<div class='item carousel-item {{ $index === 0 ? 'active' : '' }}' data-slide-number='{{ $index }}'>
<div class='video-mask'></div>
<div class='d-flex justify-content-center'>
<div class='embed-responsive embed-responsive-21by9'>
<iframe class='embed-responsive-item player' src='{{ 'https://www.youtube.com/embed/' . substr($video->url, strrpos($video->url, 'v=') + 2) }}' allowfullscreen></iframe>
</div>
</div>
</div>
#endforeach
#foreach($directoryInfo->images as $index => $image)
<div class='item carousel-item {{ ($index + sizeof($directoryInfo->videos)) === 0 ? 'active' : '' }}' data-slide-number='{{ $index + sizeof($directoryInfo->videos) }}'>
<div class='d-flex justify-content-center'>
<img src='{{ asset('storage/' . $image->path) }}' class='img-fluid' alt='imagen'>
</div>
</div>
#endforeach
<a class='carousel-control-prev' href='#sme-directory-gallery' role='button' data-slide='prev'>
<div class='rounded-circle'>
<span class='carousel-control-prev-icon' aria-hidden='true'></span>
<span class='sr-only'>Previous</span>
</div>
</a>
<a class='carousel-control-next' href='#sme-directory-gallery' role='button' data-slide='next'>
<div class='rounded-circle'>
<span class='carousel-control-next-icon' aria-hidden='true'></span>
<span class='sr-only'>Next</span>
</div>
</a>
</div>
<ul class='carousel-indicators list-inline'>
#foreach($directoryInfo->videos as $index => $video)
<li class='list-inline-item my-2 {{ $index === 0 ? 'active' : '' }}'>
<a id='carousel-selector-{{ $index + sizeof($directoryInfo->videos) }}' class='sme-gallery-anchor' data-slide-to='{{ $index }}' data-target='#sme-directory-gallery'>
<img src='{{ 'https://img.youtube.com/vi/' . substr($video->url, strrpos($video->url, 'v=') + 2) . '/mqdefault.jpg' }}' class='img-fluid'>
<div class='text-white sme-gallery-middle-icon'>
<span class='fas fa-play'></span>
</div>
</a>
</li>
#endforeach
#foreach($directoryInfo->images as $index => $image)
<li class='list-inline-item {{ $index + sizeof($directoryInfo->videos) === 0 ? 'active' : '' }}'>
<a id='carousel-selector-{{ $index + sizeof($directoryInfo->videos) }}' data-slide-to='{{ $index + sizeof($directoryInfo->videos) }}' data-target='#sme-directory-gallery'>
<img src='{{ asset('storage/' . $image->path) }}' class='img-fluid'>
</a>
</li>
#endforeach
</ul>
</div>
</div>
Javascript:
$(document).ready(function () {
$('.carousel-indicators').scrollLeft(0);
$('#sme-directory-gallery').carousel();
$('.pause-carousel').on('click', function () {
$('#sme-directory-gallery').carousel('pause'); // it works
});
$('.pause-carousel-2').on('click', function () {
$('#sme-directory-gallery').carousel('pause'); // it wont work
});
$('#sme-directory-gallery .video-mask').mouseup(function () {
var iframe = $(this).closest('.item').find('iframe');
var iframe_source = iframe.attr('src');
if (iframe_source.includes('?rel=0')) {
iframe_source = iframe_source.replace('?rel=0', '');
}
iframe_source = iframe_source + '?autoplay=1';
iframe.attr('src', iframe_source);
$(this).toggle();
$('#sme-directory-gallery').carousel('pause');
});
$('#sme-directory-gallery').on('slide.bs.carousel', function (e) {
$('#sme-directory-gallery').carousel('cycle');
var iframeID = $(this).find('iframe').attr('id');
if (iframeID != undefined) {
callPlayer(iframeID, 'stopVideo');
}
$('.video-mask').show();
$('#sme-directory-gallery').find('iframe').each(function (key, value) {
var url = $(this).attr('src');
if (url.includes('?autoplay')) {
var new_url = url.substring(0, url.indexOf('?'));
$(this).attr('src', new_url);
}
});
setTimeout(() => {
var scrollTo = $('.list-inline-item.active').position().left;
if ($('.list-inline-item.active').index() > 0) {
scrollTo = $('.list-inline-item.active').prev('.list-inline-item').position().left;
}
var finalOrFirst = 0;
if (e.direction === 'right') {
if ($('.list-inline-item.active').is(':last-child')) {
finalOrFirst = 99999;
}
} else {
if ($('.list-inline-item.active').is(':first-child')) {
finalOrFirst = -99999;
}
}
var currentScroll = $('.carousel-indicators').scrollLeft();
var scrollResult = currentScroll + scrollTo + finalOrFirst;
$('.carousel-indicators').animate({scrollLeft: scrollResult}, 500);
}, 10);
});
});
What exactly is happening here, how do I fix it?
Thanks in advance.
Try this to catch the issue:
Put console.log or alert() to check if event is triggered or not.
$('.pause-carousel-2').on('click', function () {
console.log('Button Clicked');
$('#sme-directory-gallery').carousel('pause'); // it wont work
});
Case 1:
If "Button Click" is not printed in console, then you may try:
$('body').on('click','.pause-carousel-2',function(){ ...
Case 2:
If "Button Click" is printed, then there is a workaround for this issue, which you can try.
Use Trigger
$('.pause-carousel-2').on('click', function () {
$('.pause-carousel').trigger("click");
});
and hide the Pause button which is outside
Please share your result, will try to fix your issue.
If you use .carousel() as a varaible it will work. var slider = $('#element').carousel(); And you can use in all events. slider.carousel('pause'); , for starting again: slider.carousel({'pause': false});
When you use multiple element click events:
$('#btn1, #btn2').click(function(){
slider.carousel('pause');
});
In an another event (hover):
$('#yourSlider').hover(function(){
slider.carousel('pause');
}, function(){
slider.carousel({'pause': false});
});
If you don't assign it to a variable, the carousel will be restarted
within each event.
I added an examp (it works):
$(function(){
var slider = $('#carouselExampleSlidesOnly').carousel({
interval: 1000
});
$('#pause').click(function(){
slider.carousel('pause');
});
$('#start').click(function(){
slider.carousel({'pause': false});
});
});
.carousel-item{
padding-top: 45px;
text-align: center;
height:150px;
width:100%;
color:#fff;
background-color: #666;
font-size: 2rem;
font-weight: 700;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container p-4">
<button id="pause" class="btn btn-sm btn-warning">Pause</button>
<button id="start" class="ml-2 btn btn-sm btn-primary">Start</button>
</div>
<div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel" style="width: 90%; marign:auto">
<div class="carousel-inner">
<div class="carousel-item active">
Slide 1
</div>
<div class="carousel-item">
Slide 2
</div>
<div class="carousel-item">
Slide 3
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
Set the pause to false and that will take care of the issue
$('.carousel').carousel({
pause: "false"
});
you can see an example here: https://jsfiddle.net/KyleMit/XFcSv/
I have a problem similar to this one: in some case the code doesn't work in some case works. The only difference I have found is about the presence of the class "pointer-event" in the tag of the carousel element.
To solve this problem I have use a boolean variable with the event "slide.bs.carousel" to avoid carousel to slide when paused.
HTML CODE
<section id="slideshow" class="carousel slide">
<div class="carousel-inner" id="images" >
<div class="carousel-item " >
<img src="..." class="d-block w-100" alt='bla bla bla' >
</div>
<div class="carousel-item " >
<img src="..." class="d-block w-100" alt='bla bla bla' >
</div>
<div class="carousel-item " >
<img src="..." class="d-block w-100" alt='bla bla bla' >
</div>
</div>
<a class="carousel-control-pause" href="#slideshow" role="button" >
<span class="pause-icon">
||
</span>
<span class="play-icon d-none">
|>
</span>
</a>
<a class="carousel-control-prev" href="#slideshow" role="button" data-slide="prev" >
<--
</a>
<a class="carousel-control-next" href="#slideshow" role="button" data-slide="next" >
-->
</a>
</section>
JAVASCRIPT CODE
$(document).ready(function(){
var carousel = $('#slideshow').carousel({
interval: 5000,
ride: true
});
var carousel_paused = false;
//on init the carousel is paused
$('#slideshow .carousel-control-pause').on('click', function(e){
e.preventDefault();
var hideclass= "d-none";
var pause= $(this).children(".pause-icon");
if( $(pause).is(":hidden"))
{
//play
$(pause).removeClass(hideclass);
$(this).children(".play-icon").addClass(hideclass);
carousel.carousel('cycle');
carousel_paused = false;
}
else
{
//pause
$(pause).addClass(hideclass);
$(this).children(".play-icon").removeClass(hideclass);
carousel.carousel('pause');
carousel_paused = true;
}
});
carousel.on('slide.bs.carousel', function (e) {
console.log("slide pre");
//prevent slide if paused
if(carousel_paused)
e.preventDefault();
});
carousel.on('slid.bs.carousel', function (e) {
console.log("slide done");
});
});
The code is for example and is not tested in mobile.

Replace the main image with thumbnails in Javascript

Here my script :
function changeImage(event){
event = event || window.event;
var targetElement = event.target || event.srcElement;
if (targetElement.tagName == "IMG"){
document.getElementByClass("img-big-wrap").src = targetElement.getAttribute("src");
document.getElementById("mainimageLink").href = 'link'+targetElement.getAttribute("data-link")+'.html';
}
}
Inspired of this Answer : Javascript Gallery - Main Image href change
My HTML :
<div class="gallery-wrap">
<div class="img-big-wrap">
<a id="mainimagelink" href="<?php echo $data[0][gallery][0][photo];?>">
<img class="img-big-wrap" src="<?php echo $data[0][gallery][0][photo];?>" alt="">
</div>
<div class="img-small-wrap" onclick="changeImage(event)">
<div class="item-gallery"> <img src="<?php echo $data[0][gallery][1][thumb];?>" data-link="1"> </div>
<div class="item-gallery"> <img src="<?php echo $data[0][gallery][2][thumb];?>" data-link="2"> </div>
<div class="item-gallery"> <img src="<?php echo $data[0][gallery][3][thumb];?>" data-link="3"> </div>
<div class="item-gallery"> <img src="<?php echo $data[0][gallery][4][thumb];?>" data-link="4"> </div>
</div>
</div>
The code is actualy just open me the link of the main image only
I want to change the main image with the thumbnails when I click On, I dont know if what i'm doing is the good solution
Working Plunk: http://plnkr.co/edit/pjpHBUD4yPihqr7lJKAD?p=preview
<div class="gallery-wrap">
<div>
<a id="mainimagelink" href="https://blog.conservation.org/wp-content/uploads/2014/06/ci_19290600_cropped.jpg">
<img class="img-big-wrap" src="https://blog.conservation.org/wp-content/uploads/2014/06/ci_19290600_cropped.jpg?>" alt="">
</a>
<hr/>
</div>
<div class="img-small-wrap" ">
<div class="item-gallery " onclick="changeImage(event) "> <img src="https://s5.favim.com/610/52/Favim.com-winter-nature-small-canon-eos-7d-474348.jpg " data-link="1 "> </div>
<div class="item-gallery " onclick="changeImage(event) "> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTfAMUZQLGObfUBSLgnPj5b5C7Ww2DNMtKbwkuTbglK-p1La17BnA " data-link="2 "> </div>
</div>
</div>
A couple of things you've missed.
The HTML DOM was not well constructed. The tag with id mainimagelink was left unclosed, leading to opening of the main image everytime you clicked on any image.
Not sure of your use case but I believe you were trying to create a thumbnail gallery with a preview. Added Image URLs and CSS to simulate the API response.
'img-big-wrap' class was used for the image container and the actual Image itself, which would lead to errors when you try to locate your element with js.
document.getElementByClass is not the right name for the method. I believe you were going for 'document.getElementsByClassName' which returns an array as multiple elements can have the same className.
Refer to querySelector (most useful of them all):
https://www.w3schools.com/jsref/met_document_queryselector.asp
All the best!
First of all, you have used the same class more than once and tried to access it img-big-wrap.
There is also no accessor called getElementByClass instead use
getElementsByClassName which is an array since you can have multiple divs with the same class.
Typo here "mainimageLink" which you called your div with id="mainimagelink", case matters.
I have moved onclick into JS using addEventListener which saves me passing parameters from the div.
Add an id into your thumbnail parent div myImgDiv and used it to hook an Event Listener to it.
Here is what the code looks like (Not many changes were made):
let smallImgDiv = document.getElementById('myImgDiv');
smallImgDiv.addEventListener('click', (e) => {
let targetElement = e.target || e.srcElement;
let tagName = targetElement.tagName;
if(tagName === "IMG") {
document.getElementById('bigImage').src = targetElement.getAttribute("src");
document.getElementById("mainimagelink").href = 'link' + targetElement.getAttribute("data-link") + '.html';
}
});
.img-small-wrap img{
width: 150px;
height: 150px;
}
.img-big-wrap {
height: 200px;
}
<div class="gallery-wrap">
<div class="img-big-wrap">
<a id="mainimagelink" href="#">
<img id="bigImage" class="img-big-wrap" src="http://via.placeholder.com/300.png" alt="">
</a>
</div>
<div id="myImgDiv" class="img-small-wrap">
<div class="item-gallery"> <img src="https://getuikit.com/v2/docs/images/placeholder_200x100.svg" data-link="1"> </div>
<div class="item-gallery"> <img src="https://cdn.dribbble.com/users/312581/screenshots/1676038/female-placeholder_1x.png" data-link="2"> </div>
<div class="item-gallery"> <img src="https://d30y9cdsu7xlg0.cloudfront.net/png/1134418-200.png" data-link="3"> </div>
<div class="item-gallery"> <img src="https://source.sierrawireless.com/~/media/developer%20zone/icons/sw_dz_icons_placeholder.ashx?h=240&la=en&w=240" data-link="4"> </div>
</div>

OnClick ChangeImage And URL

I have the main image and a zoom icon for it and I have an image next to the first image. I wanna write a JavaScript code where when I click on the second image it changes the first image scr and the zoom icon's href link I found a code for it, but I can't make it work. This is the code I have so far:
<script type="text/javascript">
function change(menuId, image, newImage, newUrl)
{
var img = document.getElementById(image);
img.src = newImage;
document.getElementById('d3').href = newUrl;
}
</script>
and i tried to do make it work like that
<script type="text/javascript">
function change(menuId, image, newImage, newUrl)
{
var img = document.getElementById(image);
img.src = newImage;
document.getElementById('d3').href = newUrl;
}
</script>
<div class="thumbnail">
<div id="main_img">
<img id="img" src="assets/example/latest/S8621A.png" alt=""/>
<div class="caption">
<span class="ico-block">
<a class="ico-zoom" href="assets/example/latest/S8621A.png" id="d3"><span></span></a>
</span>
</div>
</div>
</div>
<div style="text-align:center">
<div id="thumb_img">
<img src='assets/img/fekete.png' onclick='changeImage("assets/example/latest/S8621A.png")' >
<img src='assets/img/barna.png' onclick='changeImage("assets/example/latest/S8621B.png")' onclick='document.getElementById'("d3").href = '(assets/example/latest/S8621B.png)'>
</div></div>
I just don't know how it should work. I really don't understand that whole JavaScript. Can someone help me or show me how will it work? THX for the help.
As others have already said, change() should be changeImage() or vice versa.
There was no obvious target for the MenuId parameter so it's removed.
Made the zoomImage() function just for the hell of it.
Click any of the bottom images and the top one changes and the GO link's href changes as well.
The zoom icon will enlarge the top image by 50% without leaving the page.
Added 2 more functions…not sure what OP wants.
imageZoom() will use transform: scale() to zoom the image.
resetImage() will reset the image back to 128px
Snippet
img {
cursor: pointer;
}
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<script type="text/javascript">
function changeImage(newImage, newUrl) {
var img = document.getElementById('img');
img.src = newImage;
document.getElementById('goto').href = newUrl;
return false;
}
function zoomImage() {
var img = document.getElementById('img');
if (img.style.width == "192px") {
img.style.width = "128px"
} else {
img.style.width = "192px";
}
return false;
}
function imageZoom() {
var img = document.getElementById('img');
if (img.style.width == "512px") {
img.style.transform = "scale(.25)";
} else {
img.style.transform = "scale(4)";
}
return false;;
}
function resetImage() {
var img = document.getElementById('img');
img.style.width = "0px";
img.style.transform = "scale(1)"
img.style.width = "128px";
return false;
}
</script>
<div class="thumbnail">
<div id="main_img">
<img id="img" src="https://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png" alt="" width="128" />
<div class="caption">
<div class="ico-block">
<a id="goto" href="https://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png">GO</a>
<a class="ico-big" href="#" id="d3" width="32" onclick="zoomImage();">
<img src="http://icons.iconarchive.com/icons/rafiqul-hassan/blogger/32/Zoom-In-icon.png" />
</a>
<a class="ico-zoom" href="#" id="3d" width="32" onclick="imageZoom();">
<img src="https://image.freepik.com/free-icon/zoom-in-pc_318-11477.jpg" width="32" />
</a>
</div>
</div>
</div>
</div>
<div style="text-align:center">
<div id="thumb_img">
<img src='http://i44.tinypic.com/2uxz43b.jpg' onclick='changeImage("http://cnx.org/resources/b785d2ec9b6302264f1ed942f4ec1b822d6f7b4c/lena.jpg", "http://cnx.org/resources/b785d2ec9b6302264f1ed942f4ec1b822d6f7b4c/lena.jpg")' width="128">
<img src='http://www.log85.com/tmp/doc/img/perfectas/lenna/lenna1.jpg' onclick='changeImage("http://lh3.ggpht.com/_ERXQs5oLNgE/S01Ee_26lsI/AAAAAAAAAlY/1T0Dl4QJiYk/s800/lenaV.jpg", "http://lh3.ggpht.com/_ERXQs5oLNgE/S01Ee_26lsI/AAAAAAAAAlY/1T0Dl4QJiYk/s800/lenaV.jpg")'
width="128">
<button onclick="resetImage();">RESET</button>
</div>
</div>
First you need to make sure the js function works.
Second, <img src='assets/img/barna.png' onclick='changeImage("assets/example/latest/S8621B.png")' onclick='document.getElementById'("d3").href = '(assets/example/latest/S8621B.png)'> is not right, it should be
<img src='assets/img/barna.png' onclick='changeImage("assets/example/latest/S8621B.png")' onclick='document.getElementById("d3").href = "assets/example/latest/S8621B.png"'> if my understanding is right.
Small description would be: you just need to assign clicked image to zoom icon to give it toggle effect.[that we doing by getElementById("d3") part
<script type="text/javascript">
function changeImage(element,newUrl) {
element.src = newUrl;
document.getElementById("d3").href= newUrl;
}
</script>
<div class="thumbnail">
<div id="main_img">
<img id="img" src="assets/example/latest/S8621A.png" alt=""/>
<div class="caption">
<span class="ico-block">
<a class="ico-zoom" href="assets/example/latest/S8621A.png" id="d3"><span></span></a>
</span>
</div>
</div>
</div>
<div style="text-align:center">
<div id="thumb_img">
<img src='assets/img/fekete.png' onclick='changeImage(this, "assets/example/latest/S8621A.png")'>
<img src='assets/img/barna.png' onclick='changeImage(this, "assets/example/latest/S8621B.png")'>
</div>
</div></div>
This should do it:
function changeImage(element,newUrl) {
element.src = newUrl;
document.getElementById('d3').href = newUrl;
}
<div class="thumbnail">
<div id="main_img">
<img id="img" src="assets/example/latest/S8621A.png" alt="" />
<div class="caption">
<span class="ico-block">
<a class="ico-zoom" href="assets/example/latest/S8621A.png" id="d3"><span></span>
</a>
</span>
</div>
</div>
</div>
<div style="text-align:center">
<div id="thumb_img">
<img src='assets/img/fekete.png' onclick='changeImage(this, "assets/example/latest/S8621A.png")'>
<img src='assets/img/barna.png' onclick='changeImage(this, "assets/example/latest/S8621B.png")' onclick='document.getElementById' ( "d3").href='(assets/example/latest/S8621B.png)'>
</div>
</div>
Hey Robert Updated now
<!-- start: Portfolio -->
<section id="portfolio-grid" class="portfolio">
<article class="javascript html">
<script type="text/javascript">
function changeImage(element,newUrl) {
element.src = newUrl;
document.getElementById('d3').href = newUrl;
}
</script>
<div class="thumbnail">
<div id="main_img">
<img id="img" src="assets/example/latest/S8621A.png" alt="" />
<div class="caption">
<span class="ico-block">
<a class="ico-zoom" href="assets/example/latest/S8621A.png" id="d3"><span></span>
</a>
</span>
</div>
</div>
</div>
<div style="text-align:center">
<div id="thumb_img">
<img src='assets/img/fekete.png' onclick='changeImage(this, "assets/example/latest/S8621A.png")'>
<img src='assets/img/barna.png' onclick='changeImage(this, "assets/example/latest/S8621B.png")'>
</div>
</div>

Javascript in html tags to avoid repetition

I am a newbie to JavaScript and I need to use it with bootstrap for my own web page. My question is now how can I make a loop so that pictures names (stored as an array) can emerge in the right places of the HTML code so I do not have to copy the blocks of code for each picture.
For example :
<div class="row">
<div class="col-md-3 col-xs-6 portfolio-item">
<img class="img-responsive" src="01.jpg">
</div>
</div>
<div class="row">
<div class="col-md-3 col-xs-6 portfolio-item">
<img class="img-responsive" src="01.jpg">
</div>
</div>
<div class="row">
<div class="col-md-3 col-xs-6 portfolio-item">
<img class="img-responsive" src="02.jpg">
</div>
</div>
<div class="row">
<div class="col-md-3 col-xs-6 portfolio-item">
<img class="img-responsive" src="03.jpg">
</div>
</div>
As we can see here the only different text is the src.How can I store the names (paths) in an array and make a loop that changes the src property?
Thank you!
Try this demo: http://jsbin.com/pinoxeqapi/1/edit?html,output
I think that's what you're looking for.
CODE
$(function () {
var images = ["01.jpg", "01.jpg", "02.jpg", "03.jpg"];
$.each(images, function (index, element) {
var imgContainer = "<div class='row'><div class='col-md-3 col-xs-6 portfolio-item><img class='img-responsive' src='" + element + "'></div></div>";
$("body").append(imgContainer);
});
});
First Include JQuery (If not)
<script>
var srcArray = ['01.jpg', '02.jpg', '03.jpg', '04.jpg'];
$(document).ready(function () {
for (var i = 0; i < srcArray.length; i++) {
$('div.row img.img-responsive').eq(i).attr("src", srcArray[i]);
}
});
</script>
I would recommend using one of the templating frameworks described in some of the other answers. If you're interested to see how to implement this in pure JS:
var temp = document.querySelector('#portfolio-item-template');
['01.jpg', '02.jpg', '03.jpg', '04.jpg'].forEach(function(src) {
temp.content.querySelector(".img-responsive").src = src;
var newImg = document.importNode(temp.content, true);
document.querySelector('#insertion-point').appendChild(newImg);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<template id="portfolio-item-template">
<div class="row">
<div class="col-md-3 col-xs-6 portfolio-item">
<img class="img-responsive">
</div>
</div>
</template>
<div id="insertion-point">
</div>
You can use a template stored in the HTML and then generate the actual elements using an array of the image sources. Something like John Resig's micro-templates can achieve this.
<script type="text/template" id="img-tmpl">
<div class="row">
<div class="col-md-3 col-xs-6 portfolio-item>
<img class="img-responsive" src="<%= src %>">
</div>
</div>
</script>

Can't pass parameters in HTML onClick function

Me and my teammates have an issue we haven't been able to solve and hope someone can help us.
We have 4 images on the top and we want to change the content of another div when we click on them.
This is the code of the JavaScript function which puts the 4 upper images and works well. The problem appears when we try to pass parameters from the onClick() function to our modificarDetailed(). (Scroll to the right to see the most important part of img)
function insertRecommended(parent,events) {
var hola = events[0].author;
parent.append('<div class="row">\
...
<div class="col-md-3 col-sm-6">\
<img class="img-responsive img-portfolio img-hover" src="'+ events[1].image+'" alt="" onclick="modificarDetailed('+events[1].nameEvent+','+events[1].category+','+events[1].author+','+events[1].dateInit+','+events[1].image+');">\
</div>\
...
</div>')
}
This is the function which adds the HTML code of a DetailedEvent. As you can see, we try to make it dynamic and change the content of the inputs
function insertDetailedEvent(parent,event) {
parent.append('<!-- Features Section -->\
<div class="row" > \
<form id="' + "detailedform" + '">\
<div class="col-lg-12">\
<h2 class="page-header"><input type="text" name="eventname" value="'+event.eventName+'"/></h2>\
</div>\
<div class="col-md-6">\
<ul>\
<li><strong>CategorĂ­a: </strong><input type="text" name="category" value="'+event.category+'"/></li>\
<li><strong>Creador: </strong><input type="text" name="author" value="'+event.author+'"/></li>\
<li><strong>Fecha de Inicio: </strong><input type="text" name="dateInit" value="'+event.dateInit+'"/></li>\
</ul>\
<p>'+event.description+'</p>\
</form>\
</div>\
<div class="col-md-4 .col-md-offset-4">\
<img name="eventImage" class="img-responsive" src="'+event.image+'" alt="">\
</div>\
</div>\
<!-- /.row -->')
}
After that, we have this to update the content of DetailedEvent
function init(parent){
listEvent("logon",function(events){
insertRecommended(parent,events);
insertDetailedEvent(parent,events[0]);
},function(){},function(){});
}
function modificarDetailed(eventName,category,author,dateInit,image){
var documento= $("#detailedform");
documento.find('input[name="eventname"]').val(eventName);
documento.find('input[name="category"]').val(category);
documento.find('input[name="author"]').val(author);
documento.find('input[name="dateInit"]').val(dateInit);
//documento.find('img[name="eventImage"]').src(image);
}
And this is how we call the init in the html main document
<script type="text/javascript">
$(document).ready(function() {
init($('#Content'));
});
</script>
Thanks in advance.
Finally we found the solution. We saw it yesterday searching on the net but we did it wrong so it didn't work at first.
It is necessary to use '\', so this is how it was:
<img class="img-responsive img-portfolio img-hover" src="'+ events[1].image+'" alt="" onclick="modificarDetailed('+events[1].nameEvent+','+events[1].category+','+events[1].author+','+events[1].dateInit+','+events[1].image+');">\
And this is how it must be done:
<img class="img-responsive img-portfolio img-hover" src="'+ events[1].image+'" alt="" onclick="modificarDetailed(\''+events[1].nameEvent+'\',\''+events[1].category+'\',\''+events[1].author+'\',\''+events[1].dateInit+'\',\''+events[1].image+'\',\''+events[1].description+'\');">
Thanks anyway to #Barmar and #yak613 for their try.

Categories

Resources