Get next img on each click - javascript

I have a div containing imgs. I've made two arrows(prev, next) inside a large div using as background url the src of one of the imgs from the first div. I'm trying to make the next arrow, when pressed, to change the large image by using the src from the next one. And start from the beginning afterwards(loop).
JQuery:
jQuery('#next-arrow').click(function() {
var yacht_images = jQuery('#yacht-images img');
var imageUrl = jQuery(yacht_images).nextAll('.yacht-image').attr('src');
jQuery('#yacht-post-image').fadeTo('slow', 0.1, function(){
jQuery(this).fadeTo('slow', 1).fadeIn('slow').css('background-image', 'url(' + imageUrl + ')');
});
});
PHP:
<div id="yacht-post-image" style="background-image:url('<?php echo $post_thumbnail_url; ?>')">
<div id="prev-arrow"></div>
<div id="next-arrow"></div>
</div>
<?php }
global $post;
$images = get_post_meta($post->ID, 'yachts_photo', false);
if ( $images ) {
echo '<div id="yacht-images">';
foreach ($images as $image) {
if ( $image ) {
$image_url = wp_get_attachment_url($image);
echo '<img class="yacht-image" src="' . $image_url . '"/>';
}
}
echo '</div>';
}

I'm sure someone more jQuery-adept could do this better:
Demo: https://jsfiddle.net/9LeLws40/
<style>
#yacht-images img {
display: none;
}
#yacht-images,
.newimg {
height: 300px;
width: 400px;
display: inline-block;
border: 1px solid #000;
background-size: cover;
}
.newimg {
position: absolute;
display: none;
z-index: 1;
}
</style>
<div id="yacht-post-image">
<div id="prev-arrow">PREV</div>
<div id="next-arrow">NEXT</div>
<div id="curr">1</div>
</div>
<div id="yacht-images">
<img class="yacht-image" src="https://upload.wikimedia.org/wikipedia/commons/b/b4/JPEG_example_JPG_RIP_100.jpg"/>
<img class="yacht-image" src="http://dc.itamaraty.gov.br/imagens-e-textos/imagens-do-brasil/fauna/alta-fauna15.jpg/image_preview"/>
<img class="yacht-image" src="https://upload.wikimedia.org/wikipedia/commons/2/2a/Junonia_lemonias_DSF_upper_by_Kadavoor.JPG"/>
<img class="yacht-image" src="http://map.gsfc.nasa.gov/media/060915/060915_CMB_Timeline300nt.jpg"/>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
$(document).ready(function() {
var yacht_cont = $('#yacht-images');
var yacht_images = yacht_cont.children();
var curr_img = 0;
yacht_cont.css({"background-image":"url("+yacht_images[curr_img].src+")"});
$('#next-arrow').click(function() {
curr_img += 1;
var ThisImg;
if(yacht_images[curr_img] == undefined) {
curr_img = 0;
ThisImg = yacht_images[curr_img].src
$(".newimg").remove();
}
else
ThisImg = yacht_images[curr_img].src;
$("#curr").html(curr_img+1);
$('#yacht-images').append("<div class=\"newimg\" style=\" background-image: url("+ThisImg+");\"></div>");
$(".newimg").fadeIn();
});
});
</script>

I've made it work using this:
function change_main_img()
{
jQuery('#yacht-images img').click(function() {
var imageUrl = jQuery(this).attr('src');
jQuery('#yacht-post-image').fadeTo('slow', 0.1, function(){
jQuery(this).fadeTo('slow', 1).fadeIn('slow').css('background-image', 'url(' + imageUrl + ')');
});
});
}

Related

Problem with image 'rotations' within a div element

I'm using the code below to create a 'rotation' of images for display on a website. I wish for the images to display within a 'div' element...and i'm having trouble accomplishing that. It seems the problem is when I attempt to set each image as the 'background image' for the element (the line that reads "document.getElementById("rotation").style.backgroundImage = "url(toString(ImgName[number]))";). Only the initial image displays, without any 'rotation' of other images. Any help appreciated, this is becoming very frustrating.
<!DOCTYPE html>
<html>
<title>test page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<head>
<style>
div.rotation {
height: 256px;
width: 100%;
padding: 0px;
background-color: powderblue;
border-style: solid;
border-width: 5px;
border-radius: 25px;
}
</style>
</head>
<body>
<div class="w3-quarter">
<div class="w3-padding-small">
<div class="w3-center">
<div class="rotation">
<p>
<img src='images/rotation/LA_Panel.png' id='rotateImg0' alt='image rotation' />
<img src='images/rotation/McCulloch_256.png' id='rotateImg1' style='display:none;' alt='image rotation' />
<img src='images/rotation/MO_Panel.png' id='rotateImg2' style='display:none;' alt='image rotation' />
<img src='images/rotation/Rommel.png' id='rotateImg3' style='display:none;' alt='image rotation' />
</p>
</div>
</div>
</div>
</div>
</body>
</html>
<script type='text/javascript'>
var rotation = function () {
var currentImage,
images = [],
ImgName = [],
count,
hideImages,
showImage,
fn;
count = (function () {
// Figure out how many images we have on the rotation
var x = 0;
while (document.getElementById('rotateImg' + (x + 1).toString())) {
images[x] = document.getElementById('rotateImg' + x.toString());
ImgName[x] = document.getElementById('rotateImg' + x.toString()).src;
x++;
}
return images.length;
})();
hideImages = function () {
// Hide all the images
for (var i = 0; i < count; i++) {
images[i].style.display = 'none';
}
};
showImage = function (number) {
document.getElementById("rotation").style.backgroundImage = "url(toString(ImgName[number]))";
images[number].style.display = 'block';
};
fn = {};
fn.setupRotation = function () {
// Show the first image
currentImage = 0;
showImage(currentImage);
// Start the rotation
var interval = setInterval(rotation.advanceRotation, 4000);
};
fn.advanceRotation = function () {
if (currentImage + 1 == count)
currentImage = 0;
else
currentImage++;
hideImages();
showImage(currentImage);
};
return fn;
} ();
rotation.setupRotation();
</script>
One thought might be to pluck off the first child and slam him to the end of the line.
let images = document.querySelector('#images');
setInterval(() => {
let el = images.removeChild(images.childNodes[0]);
images.appendChild(el);
}, 1000);
#images {
font-size: 0;
}
.img {
display: inline-block;
width: 30px;
height: 30px;
}
<div id="images">
<div class="img" style="background-color: red"></div>
<div class="img" style="background-color: orange"></div>
<div class="img" style="background-color: yellow"></div>
<div class="img" style="background-color: green"></div>
<div class="img" style="background-color: blue"></div>
</div>

Jquery horizontal image gallery - retain clicked image to the middle

I have a horizontal image gallery, the images for which is populated from a thumbnail folder. I want to create a utility where the clicked image always remain at the middle of the thumbnail image palette. Similar to the question asked here.
A minimal version of the code is as follows:
HTML
<!DOCTYPE html>
<html>
<head>
<style>
#loaded_img_panel {
border-top: solid 0.3em #f1ded9;
display:flex;
flex-wrap: nowrap;
overflow-x:auto;
padding: 10px 0 0 0;
}
#loaded_img_panel > ul > li {
list-style: none;
}
#loaded_img_panel ul li img {
display: inline;
width: 210px;
height:175px;
cursor: pointer;
}
#loaded_img_panel img.active{
border: 0.4em solid red;
padding : 5px;
}
#loaded_img_panel > caption {
display:block;
}
#loaded_img_panel img:hover {
opacity: 0.5;
}
</style>
</head>
<body>
<div class="book-list-headbox">
<div class="page-number-box">
<label for="" id="total-page" value="" class="mb-0"></label>
<span class="separator">of</span>
<input type="text" id="current-page" value="1">
</div>
</div>
<div class="loaded_img_panel" id="loaded_img_panel">
</div>
</body>
</html>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
window.addEventListener('load', function(e) {
var matchLst = "thumb";
var project = "upload";
if (matchLst !== null && matchLst !=="") {
$.post("loadimages.php", { 'project' : project,'matchLst' : matchLst }, function(output){
$("#loaded_img_panel").html(output).show();
});
}
})
$(function(){
$('#gotoframe').change(function() {
var i = $(this).val() -1;
activeBook(i);
localStorage.setItem('clicki', i);
});
$('#loaded_img_panel').on('click', 'img', function() {
activeBook($(this).index());
});
function activeBook(i){
$('#loaded_img_panel img').removeClass('active');
var active = $('#loaded_img_panel img').eq(i).addClass('active');
var left = active.position().left;
console.log("firstleft: " + left);
var currScroll= $(".loaded_img_panel").scrollLeft();
var contWidth = $('.loaded_img_panel').width()/2;
var activeOuterWidth = active.outerWidth()/2;
left= left + currScroll - contWidth + activeOuterWidth;
$('.loaded_img_panel').animate( {
scrollLeft: left
},'slow');
}
});
</script>
loadimages.php
<?php
session_start();
$project = $_POST['project'];
$match = $_POST['matchLst'];
$_SESSION['matchLst'] = $match;
$tardir = "projects/" . $project . "/" . $match . "/thumb/*.jpg" ;
$imgdir = "projects/" . $project . "/" . $match . "/" ;
$files = glob($tardir);
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];
$filname = basename($num, ".jpg");
$imgname = basename($num);
$img = $imgdir . $imgname;
$filnam = substr($filname, -5);
$filnam = rtrim($filnam);
echo '<ul class="item" id="item">';
echo '<li class="book"><img src="'.$img.'" id="thumbNails'.$filnam.'"/>';
echo '<figcaption class="caption" name="caption">' . $filnam . '</figcaption>';
echo '</li></ul>';
}
?>
The php code renders the images from the folder. When I click on the image from the gallery, instead of providing the position of the image, I get static values till I use the scroll bar to select some of the images that were not visible onload. Those clicks returns the position values in negative. What I am trying to do is given as an example here.

jQuery an element with for a url

I have 3 divs with data-image="1" data-image="2" data-image="3".
And I have variable $img_nubmer.
I need to take the div's background-image url from element with data-image = $img_nubmer.
Something like $url = $("'.img[data-image="+$img_number+"']").css("background-image")
How could I do that please?
I would try
$img_number = 5; // just an example
$url = $("img[data-image='"+$img_number+"']").css("background-image"); // grab the background property
So for a full example:
window.getURL = function() {
$img_number = $('[type="number"]').val();
$url = $("[data-image='" + $img_number + "']").css("background-image");
$url = $url.replace('url(', '').replace(')', ''); // lose the extra details
alert($url);
}
div.image {
background-image: url('http://graph.facebook.com/205500370/picture?type=large');
height: 150px;
width: 150px;
}
div {
display: inline-block;
vertical-align: middle;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="image" data-image="5"></div>
<div>
<input type="number" value="5" />
<br>
<button onclick="getURL()">Get Image URL</button>
</div>
You can add the variable into your selector as such:
var img_number = 1;
$('img[data-image="'+img_number+'"]');
View Codepen example

how to expand onclick <video>

here's my html code:
echo "<div>";
echo '<video controls><source src="stuff/' . $entry . '"></video>';
echo "</div>";
here's my js code:
<script>
var videou = $( "video" ).attr("width", "150") + $( "video" ).attr("height", "80");
$( "video" ).click(function()
{
$(this).attr("width","500");
$(this).attr("height","500");
var open = true;
});
</script>
i want to go back to the original attributes. But i already tried everything. Should i use divs?
Expansion is a transitional event. Do you mean changing the width/height?
Here are expansion methods. As I had mention, check out jQuery's .slideDown() feature. Is this what you were looking for?
Simply replace the code for the .videocontainer with a video frame.
$(document).ready(function(){
$(function(){
var videos = $('.video'),
state = false;
videos.each(function(){
var videocon = $(this),
btn = videocon.find('.expandvideo'),
video = videocon.find('.videocontainer');
btn.on('click', function() {
if ( state == false ) {
video.slideDown('fast', function() { state = true; btn.html('Close Video'); });
} else {
video.slideUp('fast', function() { state = false; btn.html('Show Video'); });
}
});
});
});
});
.videocontainer {
display: none;
width: 500px;
height: 380px;
background-color:gray;
}
.expandvideo {
cursor: pointer;
color: blue;
}
.expandvideo:hover {
color: red;
}
<div class="video">
<span class="expandvideo">Show Video</span>
<div class="videocontainer">
<!-- Video Code -->
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Also to expand the frame look into jQuery's .animate() function.
$(document).ready(function(){
$(function(){
var videos = $('.video'),
state = false;
videos.each(function(){
var videocon = $(this),
btn = videocon.find('.expandvideo'),
video = videocon.find('.videocontainer');
btn.on('click', function() {
if ( state == false ) {
video.animate({width: '500px', height: '500px'}, 'fast', function() { state = true; btn.html('Close Video'); });
} else {
video.animate({width: '100px', height: '80px'}, 'fast', function() { state = false; btn.html('Show Video'); });
}
});
});
});
});
.videocontainer {
width: 100px;
height: 80px;
background-color:gray;
}
.expandvideo {
cursor: pointer;
color: blue;
}
.expandvideo:hover {
color: red;
}
<div class="video">
<span class="expandvideo">Show Video</span>
<div class="videocontainer">
<!-- Video Code -->
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Your question is hard to understand, but based on your js code, maybe is this what you want
<script>
var open = false;
$( "video" ).attr("width", "150");
$( "video" ).attr("height", "80");
$( "video" ).click(function()
{
if(open){
$(this).attr("width","150");
$(this).attr("height","80");
open = false;
}else{
$(this).attr("width","500");
$(this).attr("height","500");
open = true;
}
}
);
</script>
I'm not sure exactly what you are trying to achieve, as your description seems rather vague... If you are wanting a video to be displayed on the click of another element...
echo '<div id="divVideo" style="display: none;">';
echo '<video controls><source src="stuff/' . $entry . '"></video>';
echo '</div>';
echo 'Show Video';
<script>
$(document).ready(function() {
$('#aVideo').click(function(e) {
e.preventDefault();
$('#divVideo').show();
}
});
</script>
If that is not what you are trying to do, then please more descriptive and I'll try to help the best I can.

owl carousel plugin doesn't work inside a event click

i need to initialize the owl carousel inside a click event like the following code, it works in first time when I click, but when I click it again (on event div) it simply doesn't work. how can I accomplish that? is there a way to reset the owl carousel?
I added my full code to the last part of this post to understand better my pb and to test it.
Could you please help me on this? I really need this.
thanks in advance,
CAFC
source owl carousel : http://owlgraphic.com/owlcarousel/demos/customJson.html
$('#XX').click(function(e) {
e.PreventDefault;
$("#owl-demo").owlCarousel({
jsonPath: 'json/customData2.json',
jsonSuccess: customDataSuccess
});
function customDataSuccess(data) {
var content = "";
for (var i in data["items"]) {
var img = data["items"][i].img;
var alt = data["items"][i].alt;
content += "<img src=\"" + img + "\" alt=\"" + alt + "\">"
}
$("#owl-demo").html(content);
}
});
my full code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Owl Carousel - Dynamic content via JSON</title>
<!-- Owl Carousel Assets -->
<link href="../owl-carousel/owl.carousel.css" rel="stylesheet">
<link href="../owl-carousel/owl.theme.css" rel="stylesheet">
<script src="../assets/js/jquery-1.9.1.min.js"></script>
<script src="../owl-carousel/owl.carousel.js"></script>
<!-- Demo -->
<style>
#owl-demo .item {
background: #a1def8;
padding: 10px 0px;
display: block;
margin: 5px;
color: #FFF;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
text-align: center;
}
</style>
<script>
$(document).ready(function() {
$('#XX').click(function(e) {
$("#owl-demo").owlCarousel({
jsonPath: 'json/customData2.json',
jsonSuccess: customDataSuccess
});
function customDataSuccess(data) {
var content = "";
for (var i in data["items"]) {
var img = data["items"][i].img;
var alt = data["items"][i].alt;
content += "<img src=\"" + img + "\" alt=\"" + alt + "\">"
}
$("#owl-demo").html(content);
}
});
});
</script>
</head>
<body>
<div id="owl-demo"></div>
<div id='XX'>Click HERE!</div>
</body>
</html>
Here ya go:
JS:
$(document).ready(function () {
var owl = false;
$('#XX').click(function (e) {
if (owl) {
$("#owl-demo").data('owlCarousel').reinit({
jsonPath: '/echo/json',
jsonSuccess: customDataSuccess
});
} else {
owl = true;
}
$("#owl-demo").owlCarousel({
jsonPath: '/echo/json',
jsonSuccess: customDataSuccess
});
function customDataSuccess(data) {
console.log('loading Data');
data = testJSON;
var content = "";
for (var i in data["items"]) {
var img = data["items"][i].img;
var alt = data["items"][i].alt;
content += "<img src=\"" + img + "\" alt=\"" + alt + "\">";
}
$("#owl-demo").html(content);
}
});
});
The methods of reinit are found at the bottom of the documentation under 5. Owl Data methods
Demo: http://jsfiddle.net/robschmuecker/pLvdx8xx/

Categories