Swap image src after ajax request using jQuery - javascript

I need to swap the image src of an img element using jQuery. I fetch the images using $.getJSON() and this is a different one every time. I've chained this swap to the hover of an <li> element using jQuery, but sometimes it will lag a bit when the image is changed or the image isn't loaded correctly on the first hover. I need a valid solution that can help me to do the trick. Here is the code:
HTML:
<div class="col-md-2 col-lg-2 text-right portfolio-thumb">
// here I used a static img tag, but I've opted to append it everytime.
<img class="img-fluid portfolio-nav-thumb" width="80" src="">
</div>
<div class="col-md-4 col-lg-4 portfolio-nav">
<ul class="navbar-nav ml-auto">
<?php if( $portfolio->have_posts() ): while( $portfolio->have_posts() ): $portfolio->the_post(); ?>
<li class="nav-item portfolio-nav-el"><a data-id="<?php echo get_post_thumbnail_id(); ?>" class="nav-link portfolio-nav-link" href="<?php the_permalink(); ?>"><?php the_title('<h4>', '</h4>'); ?></a></li>
<?php endwhile; ?>
<?php endif; wp_reset_postdata(); ?>
</ul>
</div>
JS:
$('.portfolio-nav-el').on('hover', function(e){
e.preventDefault();
// here I empty the img container div
$('.portfolio-thumb').empty();
var id = $(this).children('.portfolio-nav-link').attr('data-id');
//console.log(id);
$.getJSON('https://localhost/wordpress/wp-json/wp/v2/media/'+id, function(response){
// here I'm adding the img element to the parent container div
$('.portfolio-thumb').html('<img class="img-fluid portfolio-nav-thumb" src="'+ response.source_url +'" width="80">');
});
});
A preload or a fade solution can be fine?

$(document).on('hover', '.portfolio-nav-el', function() {
//Enter your code here...
});
This code will work on the elements that are created after ajax

I think you answered yourself. The preload is the best solution imo. I would probably load thumbnails for all items in the list. Maybe in base64 form, store it in propriate data attribute of each item and then, on hover, use it in src of your '.portfolio-thumb' element.

Related

Pass variable between from PHP to a DIV HTML

I have a web page where I show a series of images brought from a database, these images when passing over shows you a "quick view" message (), clicking on this link shows you on the page a div with the largest image, I need when someone click on this link, in the div show me different images according to what I have clicked, this is my code
PHP/HTML CODE
if ($array->num_rows > 0) {
while($row = $array->fetch_assoc()) {
<div>
<?php echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['picture'] ).'" />'; ?>
<a href="#" class="js-show-modal1">
Quick View
</a>
</div>
}
}
JS CODE
$('.js-show-modal1').on('click',function(e){
e.preventDefault();
$('.js-modal1').addClass('show-modal1');
});
CSS
.show-modal1 {
visibility: visible;
opacity: 1;
}
HTML
<div class="js-modal1">
<img src="images/someimage.jpg">
</div>
this is what i need , when i click here : Quick View
Here shows this :
<div class="js-modal1">
<img src="data:image/jpeg;base64,'.base64_encode( $row['picture'] ).'" />
</div>
Make a counter outside the loop that we will use for indexing and targeting the correct modal.
I stored the target modal in a data-property of the <a></a> tags in which I used data-target.
if ($array->num_rows > 0) {
// initialize counter
$index = 0;
while($row = $array->fetch_assoc()) {
// use the counter in the loop, modal-".$index."
echo "
<div>
<a href='#' class='js-show-modal' data-target='modal-".$index."'>
Quick View
</a>
<div id='modal-".$index."'>
<img src='data:image/jpeg;base64,".base64_encode($row['picture'])."' />
</div>
</div>";
// increment
$index++;
}
}
Then use this script below. We added an onclick event handler to .js-show-modal which will be all the <a></a> tags. We will then get data-target property as the selector. I used toggle for switching between hide() and show().
$(document).on('click','.js-show-modal',function(e){
e.preventDefault();
var target = '#'+$(this).data('target');
$(target).toggle();
});

change main image by click left or right arrow or selecting actual image from thumbnail gallery in PHP

i'm developing a pdf book page viewer, i have many books that has more than 100 pages in my mysql database. so i fetch the book pages into my thumbnail gallery and if i select that image it will add img src to main image and display it on main image div, that works perfectly, here i have right and left arrow buttons next to main image, if i click these buttons the image should select next image or previous image. i was trying to get the idea and trying different source i could not get the output, please help me with this, i have added my codes bellow,
PHP
<button class="left-arrow" id="left-arrow">Left</buttom>
<img src="" alt="book" class="main-img" id="main-img">
<button class="right-arrow" id="right-arrow">Right</buttom>
<ul class="book-list id="book-list">
<?php if ($total_page > 0) : ?>
<?php foreach ($results as $row) : ?>
<li class="book p-2">
<span class="page-number"><?php echo $page_num++ ?></span>
<img src="<?php echo PAGE_URL . "/" . $b_id . "/" . $row->page_name ?>" alt="Book Image">
</li>
<?php endforeach ?>
<?php endif ?>
</ul>
JavaScript
<script type="text/javascript">
var bookPageList = $('#book-list');
$(bookPageList).click(displayImage);
function displayImage(e) {
if (e.target !== e.currentTarget) {
var target = e.target;
var src = target.src;
// console.log(src);
$('#main-img').attr('src', src);
}
}
</script>
I have fixed this issue in this link, hope this help to other newbies
Change image by selecting from thumbnail or next prev buttons

"Fotorama" jquery plugin size glitch

Here's the screencast: http://screencast.com/t/NK7l2VfT
And the code:
<div class="fotorama"
data-allowfullscreen="native"
data-nav="thumbs"
data-hash="true"
data-loop="true"
data-keyboard="true"
data-width="100%"
data-ratio="800/600"
>
<?php
for ( $i=1; $i<12; $i++ ) {
echo '
<a href="http://s.fotorama.io/okonechnikov/'.$i.'.jpg">
<img src="http://s.fotorama.io/okonechnikov/'.$i.'-thumb.jpg">
</a>';
}
?>
</div>
Seems like if thumbnail loads faster than main image, the #fotorama div sometimes takes it's size from thumbnail. Any ideas how to fix it?
Looks like adding
data-auto="false"
data-width="100%"
data-ratio="800/600"
And moving fotorama initialization to
$(document).ready(function() {});
fixes the problem.

How to insert PHP snip into a Javascript script

The variable in $pieces[12] is the url of an image on my server, some times when the page loads there is a broken image. My script is suppose to find the broken image error if there is one and replace it with $pieces[12] again. If that sounds right. But I don't know how to do it with my code.
<div class="right_ad" id="right_ad">
<script>
<img src="<?php echo $pieces[12]; ?>"
onError="this.onerror=null;this.src='<?php echo $pieces[12]; ?>';"
style="width: 100%;max-height: 100%"/>
</script>
</div>
You should urlencode those values. My tip is that there are special values in your filenames.
function onError_run_this_func(){
//get your new image url with ajax function
//or if you already have it in $pieces[12] then use it.
$.('.image-class).attr('src', '<?php echo $pieces[12]; ?>');
}
<div class="right_ad" id="right_ad"><script><img class="image-class" src="`<?php echo $pieces[12]; ?>" onError="onError_run_this_func()" style="width: 100%;max-height: 100%"/></script> </div>`

Need help making jQuery loop for basic .fadeIn()/.fadeOut() slider

I'm new to jQuery and am having trouble figuring out the right way to loop a set of code for a basic carousel/banner rotator. I've tried a few versions of "for" statements and .each(), but I can't get it to work on my own so I'm reaching out for help.
Here's my code so far:
$('.next-1').click(function () {
$('.featured-1').fadeOut(500,function(){
$('.featured-2').fadeIn(500,function(){
$('.featured-2').toggleClass("hide");
});
});
});
$('.next-2').click(function () {
$('.featured-2').fadeOut(500,function(){
$('.featured-3').fadeIn(500,function(){
$('.featured-3').toggleClass("hide");
});
});
});
And then a similar code block for going back within the slider:
$('.prev-2').click(function () {
$('.featured-2').fadeOut(500,function(){
$('.featured-1').fadeIn(500,function(){
$('.featured-2').toggleClass("hide");
});
});
});
$('.prev-3').click(function () {
$('.featured-3').fadeOut(500,function(){
$('.featured-2').fadeIn(500,function(){
$('.featured-3').toggleClass("hide");
});
});
});
This code does work right now, I just don't want to have to output so many unnecessary lines of code when I know I could loop it. I'd like to be able to loop until there are no more "featured-n" divs to cycle through (being able to cycle around to the beginning would be great too!)
Here's the PHP/HTML I'm using to generate each "featured-n" div block:
function home_slider_loop() {
$count = 0;
query_posts ('tag=slider');
if (have_posts()) : while (have_posts()) : the_post();
$count++;
?>
<div class="featured-post featured-<?php echo $count; if ($count>1) { echo ' hide';}?>">
<div class="featured-header">
<h1 class="featured-title"><?php the_title(); ?></h1>
<p class="author">Written by Evan Luzi</p>
</div>
<div class="image-wrap">
<?php the_post_thumbnail('full', array('class' => 'slider-image')); ?>
<div class="slider-nav">
<div class="featured-prev prev-<?php echo $count; ?>"></div>
<div class="featured-next next-<?php echo $count; ?>"></div>
</div><!--End Navigation-->
</div><!--End Image <?php echo $count; ?>-->
<div class="featured-footer">
<?php the_excerpt(); ?>
<a class="more-link" href="<?php the_permalink(); ?>" alt="<?php the_title(); ?>" >Read more</a>
</div>
</div><!--End Featured <?php echo $count; ?>-->
<?php
endwhile;
endif;
}
Here's a sample of one of the static HTML outputs (just imagine this iterated several times with the "featured-n" classes incrementing:
<div class="featured-1">
<div class="featured-header">
<h1 class="featured-title">5 Useful Cinematography Apps for iOS You Should Download Today</h1>
<p class="author">Written by Evan Luzi</p>
</div>
<div class="image-wrap">
<img width="1018" height="416" src="http://www.tbabdev.com/wp-content/uploads/2013/07/cinematography-apps-8-hero.jpg" class="slider-image wp-post-image" alt="cinematography-apps-8-hero" />
<div class="slider-nav">
<div class="featured-prev prev-1"></div>
<div class="featured-next next-1"></div>
</div><!--End Navigation-->
</div><!--End Image 1-->
<div class="featured-footer">
<p>The devices we have in our pockets, the ones that can run these apps, these are the new leathermans. They have everything we need. They eliminate the need to carry paper manuals and enable us to do complex timelapse calculations in a fraction of the time as a paper and pen.</p>
<a class="more-link" href="http://www.tbabdev.com/?p=27" alt="5 Useful Cinematography Apps for iOS You Should Download Today" >Read more</a>
</div>
</div><!--End Featured 1-->
You can see the code in action at http://www.tbabdev.com/
Thank you in advance for your help and please be kind to a n00b :)
Use something like this :
$('.nav .prev').click(function(){
activeBlock = $('.featured.active');
prevBlock = activeBlock.prev('.featured');
activeBlock.fadeOut('slow',function(){
prevBlock.fadeIn().addClass('active');
}).removeClass('active');
});
$('.nav .next').click(function(){
activeBlock = $('.featured.active');
nextBlock = activeBlock.next('.featured');
activeBlock.fadeOut('slow',function(){
nextBlock.fadeIn().addClass('active');
}).removeClass('active');
});
Html
<div class="nav">
<div class="prev"> </div>
<div class="next"> </div>
</div>
<div class="featured-post featured <?php if($count>1) echo 'hide' ?>">
<div class="featured-header">
<h1 class="featured-title"><?php the_title(); ?></h1>
<p class="author">Written by Evan Luzi</p>
</div>
<div class="image-wrap">
<?php the_post_thumbnail('full', array('class' => 'slider-image')); ?>
</div>
<!--End Image <?php echo $count; ?>-->
<div class="featured-footer">
<?php the_excerpt(); ?>
<a class="more-link" href="<?php the_permalink(); ?>" alt="<?php the_title(); ?>" >Read more</a>
</div>
</div>
You could do it this way :
$('.featured-next, .featured-prev').click(function () {
//find out if the clicked element is a prev or next element, extract the last part, will be useful later
var direction = $(this).hasClass("featured-next") ? "next" : "prev";
//select the ".featured-n" block which is the super-parent of clicked element
var $fullBlock = $(this).closest('div[class^="featured-"]'); //or add a class here to make your life easier
//fade out full block
$fullBlock.fadeOut(500, function () {
//search for the next element and show it
//note that $fullBlock.next() => $fullBlock["next"]() => $fullBlock[direction]()
$fullBlock[direction]().fadeIn(500, function () {
//toggle the class "hide" of the element next to fullBlock
$(this).toggleClass("hide");
});
});
});
Explanation:
You can join up both prev and next events together.
Then, you have to check if its a next or a prev element. Set that to a variable called direction. We'll be using this to find out if we have to use prev() or next() when we're trying to fadeIn featured-n divs.
Find the parent with the class set to featured-n (in your case its the superparent). It might be better if you give a common class to all these elements so that we can stop using 'div[class^="featured-"]' selector, which is slightly inefficient.
Fade out the superparent.
In the callback, based on the direction variable, we'll have to decide if the carousel is gonna go to prev block or next block, something like this :
if(direction === "prev")
{
$fullBlock.prev().fadeIn(//your code)
}
else
{
$fullBlock.next().fadeIn(//your code)
}
You must also know that, in an object like this :
var data = {"name" : "Blah Blah"}
To get the "Blah Blah" out, we can say
data.name
or we could say :
data["name"]
So based on this, in our situation, instead of
$fullBlock.prev()
Or we could say
$fullBlock["prev"]()
Which is what direction variable contains. So finally, we could do this to select the next/prev element based on what was clicked :
$fullBlockdirection
Show the prev/next element.
Add/remove "hide" class.
Hope this helped!

Categories