Download pictures in modal ONLY when modal is displayed - javascript

Okay, so I want to have a LOT of buttons on a page, which each open a different modal, populated with a gif with php. As you may have guesse, downloading a lot of quite big gifs takes a ton of time.
Solution: load the gifs only when the modal containing them is actually displayed. I was advised to use the following jQuery snippet:
echo '<script>' . "\r\n";
echo '$("#btn_'.$id.'").click(function(){' . "\r\n";
echo '$("#img_'.$id.'").attr("src", "'.$id.".gif" . '"); });';
echo '</script>' . "\r\n" . "\r\n";
More readable clean, PHP-free version:
<script>
$("#btn_id").click(function(){
$("#img_id").attr("src", "id.gif"); });
</script>
The id is replaced with an actual id in php of course.
Now this snippet doesn't actually PULL the gif from the server, so in the end nothing gets displayed at all...
edit: more code
<button id="img_id" class="modalbutton" style="background-image: url(thumbs/id.gif); cursor:pointer;" onclick="document.getElementById('modal_id').style.display='block'"></button>
<div id="modal_id" class="w3-modal w3-animate-zoom" onclick="this.style.display = 'none'">
<span id="span_id" class="w3-closebtn w3-hover-red w3-container w3-padding-16 w3-display-topright">×</span>
<div class="modal-content" onclick="this.style.display='none'"><img id="img_id" src=""></div>
</div>
<script>
$("#btn_id").click(function(){
$("#img_id").attr("src", "id.gif"); });</script>
Demo

$(document).ready(function() {
$("button").click(function(event){
var $id = event.target.id;
document.getElementById('modal_'+$id).style.display='block';
var $image = $('#img_'+$id);
var $downloadingImage = $('#imagehelper_'+$id);
$downloadingImage.attr('src', $id+'.gif');
$downloadingImage.on('load', function() {
$image.attr('src', $id+'.gif');
}).each(function() {
if(this.complete) $(this).load();
});
});
});
The script gets the id of the calling element, so I don't need a lot of different snippets.

Related

How to make a div refresh?

So this is my button div inside a PHP function called getDetails().
<div class='detail_cart'>
<a href='detail.php?add_cart=$prod_id'>
<button id='detail_button_add'>Add to cart</button>
</a>
</div>
Based on ip address, it counts how many products you've added in the cart and display them to my shop cart icon.
Every time the button is pressed it adds the product into a database but i need refresh page in order to see the updated count.
echo "<div id ='total_cart'>";
echo $count_cart =mysqli_num_rows($run_cart);
echo "</div>";
I tried to fix but no chance..
<script type= "text/javascript">
$(document).ready(function(){
$("#detail_button_add").bind("click",function(){
$("#total_cart").load("header.php");
});
});
</script>
"header.php" is the header section of my PHP.
You need to add an clear div with an span inside. You will get the data from an API in this case your header.php that returns 1,2 or any number and that will be displayed.
Your header.php
echo mysqli_num_rows($run_cart);
http_response_code(200);
exit;
<div id="total_cart">
<span id="total_cart_num"></span>
</div>
<div>
<a href="detail.php?add_cart=<?=$prod_id ?>">
<button id="detail_button_add">Add to cart</button>
</a>
</div>
<script>
document.querySelector("#detail_button_add").addEventListener("click", function(){
refreshCart();
});
function refreshCart(){
const xhr = new XMLHttpRequest();
// Add link to your Site that returns the count
xhr.open("GET", "header.php"); // Header returns Like 1,2,3 or any Number
xhr.addEventListener("load", function(){
if(this.status == 200){
document.querySelector("#total_cart_num").innerHTML = this.responseText;
} else {
alert("An error as been triggered!");
}
});
xhr.send();
}
</script>
If you mean that this is header.php:
echo "<div id ='total_cart'>";
echo $count_cart =mysqli_num_rows($run_cart);
echo "</div>";
and you do this:
$("#total_cart").load("header.php");
the result would be:
<div id ='total_cart'>
{content from header.php}
</div>
e.g.
<div id ='total_cart'>
<div id ='total_cart'>
{count of cart}
</div>
</div>
The solution is to skip the creation of div in the header.php:
(create that div elsewhere)
//remove echo "<div id ='total_cart'>";
echo $count_cart =mysqli_num_rows($run_cart);
//remove echo "</div>";
If you don't get your click event to work, you might need to use on("click"... instead of bind("click"...
(on also works on dynamically created html elements (with content))
$(document).ready(function(){
$("#detail_button_add").on("click",function(){
//This header.php should NOT include the actual html-element (div) jsut the
//content you want INSIDE the htm-element with id #total_cart
$("#total_cart").load("header.php");
});
});
Another thing with your first code-snippet is that your link won't work:
<a href='detail.php?add_cart=$prod_id'>
It should be (taking for granted you have the code in a php-file)
<a href='detail.php?add_cart=<?php echo $prod_id;?>'>

How do I trigger this hover function each time a new image has focus?

How can I hide all the images in a recordset except the image with the mouse hover on?
Images are displayed from the database and I am trying to manipulate how the images respond when a user hovers on any particular image.
Based on what I have read here on stackoverflow I came up with the following that actually works but with one limitation
On page load it works fine but once you start moving from image to image nothing happens.
I want only the active or image with hover to show while hiding the rest.
$(document).ready(function() {
$('.teamDisplay').hover(function(){
var infoFont = $(".imageDiv")
var $imgLink = $(this).children(infoFont).attr("data-imgPath");
$('.memberPicBg').css('background-image', 'url(' + $imgLink + ')');
$('.teamDisplay').addClass('imageDivOff');
$(this).addClass('imageDivOn');
}, function(){
$('.memberPicBg').css('background-image', 'url(' + $imgLink + ')');
$('.teamDisplay').addClass('imageDivOn');
$(this).addClass('imageDivOff');
});
});
I am also using css to show or hide the images but the hover function appears to work just once on page load.
How do I trigger this hover function each time a new image has focus?
This is the website with the feature I hope to replicate
UPDATE
The html code
`<div class="memberPicBg">
<?php do { ?>
<span class="teamDisplay">
<?php
// Show If File Exists (region1)
if (tNG_fileExists("../images/team/", "{members.tmemberphoto}")) {
?>
<span class="imageDiv" data-imgPath="../images/team/<?php echo $row_members['tmemberphoto']; ?>">
<span class="teamMemberNameH"><?php echo $row_members['tmember']; ?></span>
<span class="teamMemberTitleH"><?php echo $row_members['tmemberposition']; ?></span><br /><br />
<img src="../images/team/<?php echo $row_members['tmemberphoto']; ?>" alt="<?php echo my_meta_description($row_members['tmember'],6); ?>" border="0" /> </span>
<?php
// else File Exists (region1)
} else { ?>
<span class="teamMemberNameH"><?php echo $row_members['tmember']; ?></span>
<span class="teamMemberTitleH"><?php echo $row_members['tmemberposition']; ?></span>
<?php }
// EndIf File Exists (region1)
?>
</span>
<?php } while ($row_members = mysql_fetch_assoc($members)); ?>
</div>`
NB: apologising if I am not clear enough.

Why is jQuery(document).ready not working? / How do I add CSS to an element in jQuery?

I'm new to jQuery and I'm having problem with a piece of code.
I'm trying to add Image Power Zoomer v1.2 to my website, which works on the main image, but not the rollover image! The rollover image changes, but power zoomer only shows the loading image.
This is an example URL: Example1
This is my code:
<script type="text/javascript">
var bufferImage = new Array();
function Buffer(filename) {
var i = bufferImage.length;
bufferImage[i] = new Image();
bufferImage[i].src = filename;
}
function showImage(filename) {
document.images[Image_Name].src = filename;
}
Image_Name = "image_pal";
Buffer("thumbnail.php?pic=<? echo $image_pal['media_url'];? >&w=600&sq=Y");
jQuery(document).ready(function($){ //fire on DOM ready
$('#myimage').addpowerzoom({
powerrange: [2,8],
largeimage: null,
magnifiersize: [200,200] //<--no comma following last option!
})
})
</script>
<? $sql_image_pal=$db->query("SELECT media_url FROM " . DB_PREFIX . "auction_media WHERE auction_id='" . $item_details['auction_id']."'AND media_type=1 ORDER BY media_id ASC ");
$image_pal=$db->fetch_array($sql_image_pal);
$sql_image=$db->query("SELECT media_url FROM " . DB_PREFIX . "auction_media WHERE auction_id='" . $item_details['auction_id']."'AND media_type=1 ORDER BY media_id ASC ");?>
<div align="center" class="image_pal">
<? if (empty($image_pal['media_url'])) {?>
<img src="themes/<?=$setts['default_theme'];?>/img/system/noimg.gif" name="image_pal" width="600" />
<? } else {?>
<img id="myimage" src="thumbnail.php?pic=<?=$image_pal['media_url'];?>&w=600&sq=N" border="0" alt="<?=$item_details['name'];?>" name="image_pal" />
<? }?>
</div>
<div class="list_carousel_img" align="center">
<ul id="small_img">
<? while($image=mysql_fetch_array($sql_image)){?>
<? $ad_img=$image['media_url'];?>
<li class="small_img">
<a href="thumbnail.php?pic=<? echo $ad_img;?>" onmouseover="showImage('thumbnail.php?pic=<?=$image['media_url'];?>&w=600&sq=Y')"class="lightbox" rel="thumbnail_images" ><img src="thumbnail.php?pic=<?=$image['media_url'];?>&w=60&sq=Y" border="0" alt="<?=$item_details['name'];?>"/></a>
</li>
<? } ?>
</ul>
<div class="clearfix"></div>
<a id="prev_img" class="prev_img" href="#"></a>
<a id="next_img" class="next_img" href="#"></a>
<? if ($setts['lfb_enabled'] && $setts['lfb_auction']) { ?>
<div><img src="themes/<?=$setts['default_theme'];?>/img/pixel.gif" width="1" height="5"></div>
<? include("scripts/scroller/show_rep_details.php"); ?>
<? } ?>
I'm having trouble with jQuery Selectors. I have looked all over the web, spent many hours, but with no joy.
This is the site i got the Image Power Zoomer v1.2 from:
dynamicdrive.com
Question #2
Like i said im a newbie but i think my problems here jQuery selector these are some examples but i do not know what i need to add from my code
<script type="text/javascript">
jQuery(document).ready(function($){ //fire on DOM ready
$('img.showcase').addpowerzoom() //add zoom effect to images with CSS class "showcase"
$('#gallerydiv img').addpowerzoom() //add zoom effect to all images inside DIV with ID "gallerydiv"
})
</script>
What do i need to add here
$('????????????').addpowerzoom()
Thanks For all your help
jQuery(document).ready(function($){ //fire on DOM ready
==>
$(document).ready(function(){ //fire on DOM ready
Unless you changed your jQuery selector, this is the default
Because you asked another question in the answers (and even got an upvote?)
What do i need to add here
$('????????????').addpowerzoom()
This is my answer to that question:
$("img").each(function(){
$(this).addpowerzoom();
});
like in this demo: http://jsfiddle.net/u7w0ppq9/ with adding class instead of powerzoom (I do not have that library so, but it's basically the same)

Button to reload the contents of a div which contains php

I have a div containing php that loads a random image from a directory. This bit works fine when i reload the page. The code:
<div id="imageArea">
<?php
$dir = 'images/assets/';
$images = scandir($dir);
$i = rand(2, sizeof($images)-1);
?>
<img src="images/assets/<?php echo $images[$i]; ?>" alt="<?php echo str_replace(array('.jpg', '.png', '.gif'), '', $images[$i]); ?>"/>
</div>
And further down the page i have another div that contains a button. I want it so that when people click this button it loads a new random image, i guess it would reload the div, but i don't want it to reload the page, is that possible? The button:
<div id="newPic">
<input type="button" value="Reload" id="Reload"/>
</div>
I have tried:
<script>
$(document).ready(function(){
$("#Reload").click(function(){
$("#imageArea").html("result reloaded successfully");
});
});
</script>
and:
$(document).ready(function(){
$("#Reload").click(function(){
$("#imageArea").html(ajax_load).load(loadUrl);
});
});
I am new to php and javascript and so i have been following other peoples instructions.
Thank you
split your php script to another file (just echo the img tag), and then use ajax to call that page.
$("#reload").click(function(){
$.ajax({
url:"demo.php",success:function(ajax_load){
$("#imageArea").html(ajax_load)
}});
});
php file
<?php
$dir = 'images/assets/';
$images = scandir($dir);
$i = rand(2, sizeof($images)-1);
?>
<img src="images/assets/<?php echo $images[$i]; ?>" alt="<?php echo str_replace(array('.jpg', '.png', '.gif'), '', $images[$i]); ?>"/>
have you tried to use ajax to update the div with the image?
here's the code
$(document).ready(function(){
$('#clickme').click(function(){
var number = 1 + Math.floor(Math.random() * 10);
$('#contentimg').attr('src','0'+number+'.jpg');
});
});
this would work given that the images are in the same folder else give the src of image accordingly

javascript lightbox2 - how to add class to the opened img?

I am having trouble with the lightbox2 plugin.
I have an image who has class on it, and I want that the class will also be added when the image opened in lightbox.
is it possible?
<a href="fileUpload/uploads/<?php echo $picture['gallery_src']; ?>" data-lightbox=<?php echo '"image-'.$picture['gallery_id'].'"' ?>>
<img src=<?php echo '"fileUpload/uploads/'.$picture['gallery_src'].'"';?> id="filter-target" style="width:600px;">
</a>
Here's a cleaned up version of your PHP. Remember to remove your duplicate IDs
echo '<a href="fileUpload/uploads/'.$picture['gallery_src'].'" data-lightbox="image-'.$picture['gallery_id'].'">';
echo '<img src="fileUpload/uploads/'.$picture['gallery_src'].'" id="filter-target" style="width:600px;">';
echo '</a>';
You can add classes and data attributes to the image being viewed by running the following code:
$('body').on('click', 'a[rel^=lightbox], area[rel^=lightbox], a[data-lightbox], area[data-lightbox]', function(e) {
$('#lightbox .lb-image')
.addClass('filter-blur')
.data('pb-blur-amount', 5);
});
Here's a demo

Categories

Resources