I have a web page that includes 10's of thousands of images. Sometimes the image isn't available so a broken image is displayed in the clients browser.
The broken image is in the following URL format: www.domain.com/t.php?src=p/dd5e5b08_1.jpg.
How do I use jQuery to get the set of images, filter it to broken images then replace the src?
The following does not work:
above the closing </head> tag
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
above the closing tag
<script type="text/javascript">
$(window).load(function() {
$("img").each(function(){
var image = $(this);
if(image.context.naturalWidth == 0 || image.readyState == 'uninitialized'){
$(image).unbind("error").attr("src", "/images/no_image.png");
}
});
});
</script>
This code might help you:
function imgError(image){
image.onerror = "";
image.src = "/images/noimage.gif";
return true;
}
<img src="image.png" onerror="imgError(this);"/>
Try CodeFiddle Demo
This may help you:
$(document).ready(function () {
let images = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg'];
let image_html = '';
$.each(images, (key, value) => {
image_html += '<img src="img/' + value + '"/>';
});
$('#imgcontainer').html(image_html);
$('img').on('error', function () {
$(this).replaceWith('<img src="img/no-photo.jpg"/>');
});
});
Related
I am looking to create sound buttons.
Have used the answer here:
Buttons click Sounds
and implemented it so that the buttons are divs and created dynamically from a MySQL DB.
Does anyone know how to preload that list of sounds on page load?
Also, I want to apply a CSS class to the div when clicked and then when the audio finishes, want it to switch back to the original CSS class.
This is what I have tried. The sounds play correctly but the onended fuction does not fire.
<script type='text/javascript'>
$(window).load(function(){
var baseUrl = "http://[URL HERE]";
var audio = [<?php echo $audiostring; ?>];
$('div.ci').click(function() {
var i = $(this).attr('id').substring(1);
mySound = new Audio(baseUrl + audio[i-1]).play();
mySound.onended = function() {
alert("The audio has ended");};
});
});
</script>
If you are using HTML5 audio you can do something like the following:
mySound.addEventListener("ended", function()
{
alert("The audio has ended");
});
Edit:
Try changing the way you create the audio tag, as referenced here.
$('div.ci').click(function() {
var i = $(this).attr('id').substring(1);
mySound = $(document.createElement('audio'));
mySound.src = baseUrl + audio[i-1];
mySound.play();
mySound.addEventListener("ended", function()
{
alert("The audio has ended");
});
});
<audio> and new Audio() should be the same but it doesn't look
like that is the case in practice. Whenever I need to create an audio
object in JavaScript I actually just create an element like
this:
The ended event is created based on .currentTime attribute. event-media-ended
the canplaythrough event was used to knowing when the browser has finished downloading the audio file and we can play
code complete use closest
<style type="text/css">
body{background: #aaa;color:#fff;}
div
{
width: 100px;
height: 100px;
background: #dda;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div >
</div>
<div >
</div>
<div >
</div>
<script type="text/javascript">
$(window).load(function(){
var audioFiles = [
"http://www.soundjay.com/button/beep-01a.mp3",
"http://www.soundjay.com/button/beep-02.mp3",
"http://www.soundjay.com/button/beep-03.mp3",
"http://www.soundjay.com/button/beep-05.mp3"
];
function Preload(url) {
var audio = new Audio();
// once this file loads, it will call loadedAudio()
// the file will be kept by the browser as cache
audio.addEventListener('canplaythrough', loadedAudio, false);
audio.src = url;
}
var loaded = 0;
function loadedAudio() {
// this will be called every time an audio file is loaded
// we keep track of the loaded files vs the requested files
loaded++;
if (loaded == audioFiles.length){
// all have loaded
init();
}
}
var player = document.createElement('audio');
function playAudio(index) {
player.src = audioFiles[index];
player.play();
}
function init() {
$('div').click(function(event) {
$(this).css('background', 'blue');
playAudio(Math.floor(Math.random()*audioFiles.length));
player.addEventListener("ended", function(){
player.currentTime = 0;
$(event.target).closest('div').css('background', '#dda');
});
});
}
// We begin to upload files array
for (var i in audioFiles) {
Preload(audioFiles[i]);
}
});
</script>
I use a captcha in my login form and I want to refresh the captcha when I click the captcha itself!but it doesn't work!
my html code:
<cite class="fr">
<img id="captcha_img" src="securimage/securimage_show.php" alt="点击图片刷新验证码" />
</cite>
my jquery code:
$('#captcha_img').click(function(){
//alert("hh");
$('#captcha_img').attr("src","securimage/securimage_show.php");
});
I also search some docs about this question and try some other ways,but it still doesn't work,can someone give me some ideas?
Both methods below should work ( uncomment one by one and try it ):
jQuery(function ($) {
$('#captcha_img').on( 'click', function() {
// $(this).attr( "src","securimage/securimage_show.php?"+Math.random() );
// $(this).attr( "src","securimage/securimage_show.php?"+new Date().getTime() );
});
});
Browser is probably caching image. Try this:
$('#captcha_img').click(function() {
var imageUrl = 'securimage/securimage_show.php?' + new Date().getTime();
$(this).attr('src', imageUrl);
});
DEMO
$(function () {
$('#foo').click(swapImages);
var secondImg = 'http://digital-photography-school.com/wp-content/uploads/2013/03/Acorn256.png';
function swapImages() {
var img = $("<img id='foo' src='" + secondImg + "' />");
$(this).replaceWith(img);
$(img).click(swapImages);
}
});
$('#captcha_img').click(function(){
//alert("hh");
$('#captcha_img').attr("src","securimage/securimage_show.php");
return false;
});
Or use e.preventDefault() like
$('#captcha_img').click(function(e){
e.preventDefault();
$('#captcha_img').attr("src","securimage/securimage_show.php");
//return false;
});
tell me if that works. In this case, return false will work just fine because the event doesn't need to be propagated.
This is "my code" for pulling images from Facebook and displaying them.
But I want to wrap images around < a href="image.source" class="highslide" onclick="return hs.expand(this) >
Please help me outputting:
<a href="image.source" class="highslide" onclick="return hs.expand(this)>
<img src"image.source" width="167" height="167">
</a>
Original code:
<script type="text/javascript" src="underscore-min.js"></script>
<script type="text/javascript">
$.getJSON('http://graph.facebook.com/261512740659107/photos').then(function (response) {
// 0-8, 0 returns the largest available images, 8 the smallest
var imageIndex = 4;
var images = _(response.data)
.chain()
.pluck('images')
.pluck(imageIndex)
.value();
console.log(images);
_(images).each(function (image) {
$('#image-container').append(
$('<img>').attr('src', image.source).attr('height', 167).attr('width', 167));
});
});
</script>
You can use the jQuery wrap() function to put the <a> tag around your <img> tags.
Just use appendTo() instead to get the instance of the new element so that you can then wrap() it.
$.getJSON('http://graph.facebook.com/261512740659107/photos').then(function (response) {
// 0-8, 0 returns the largest available images, 8 the smallest
var imageIndex = 4;
var images = _(response.data)
.chain()
.pluck('images')
.pluck(imageIndex)
.value();
_(images).each(function (image) {
$($('<img>').attr({'src': image.source, 'height': 167, 'width': 167})).appendTo('#image-container').wrap('<a href="' + image.source + '" class="highslide" onclick="return hs.expand(this);" />');
});
});
I'm writing out a javascript string to be parsed by jquery - it works fine as an alert but not in the jquery load function
PHP:
$imgData = 'http://www.domain.com/_image.php/_MG_4156.jpg' ;
which is a php script to generate a thumbnail on the fly
<script type='text/javascript' language='javascript' charset='utf-8'>
<!--
var chart1img_".$i_gall." = new Image();
var imgData = '".$imgData."';
$(chart1img_".$i_gall.").load(function () {
$(this).hide();
$('#thumb_img_div_".$i_gall."').removeClass('loading').append(this);
$(this).fadeIn();
}).error(function () {
// notify the user that the image could not be loaded
alert(imgData);
}).attr('src', imgData);
//}).attr('src', 'http://www.domain.com/_image.php/_MG_4156.jpg');
//-->
</script>";
If I hardcore the string it works.
If I use it as the imgData variable it fails, but the alert works using imgData
Tried string combos all ways. Defeated. Any ideas?
you need add php tags in your code
<script type='text/javascript' language='javascript' charset='utf-8'>
<!--
var chart1img_"<?php echo $i_gall;?>" = new Image();
var imgData = '<?php echo $imgData?>';
$("chart1img_<?php echo $i_gall;?>").load(function () {
$(this).hide();
$('#thumb_img_div_<?php echo $i_gall;?>').removeClass('loading').append(this);
$(this).fadeIn();
}).error(function () {
// notify the user that the image could not be loaded
alert(imgData);
}).attr('src', imgData);
//}).attr('src', 'http://clients.flatearth.co.uk/benhopper/project/_image.php/_MG_4156.jpg');
//-->
</script>";
Using closures will give you a cleaner code.
Also, use json_encode to send values to JavaScript.
For example,
echo "
<script type='text/javascript'>
(function() {
var image = new Image(),
imgData = " . json_encode($imgData) . ",
i_gall = " . json_encode($i_gall) . ";
$(image).load(function () {
$(this).hide();
$('#thumb_img_div_' + i_gall).removeClass('loading').append(this);
$(this).fadeIn();
}).error(function () {
// notify the user that the image could not be loaded
alert(imgData);
}).attr('src', imgData);
})();
</script>";
This minimizes the number of embedded PHP value be defining them as JavaScript variables.
You can also put them in functions:
<script type='text/javascript'>
function loadAndShowImage(imgData, i_gall) {
var image = new Image()
$(image).load(function () {
$(this).hide();
$('#thumb_img_div_' + i_gall).removeClass('loading').append(this);
$(this).fadeIn();
}).error(function () {
// notify the user that the image could not be loaded
alert(imgData);
}).attr('src', imgData);
}
</script>
and then output just the dynamic parts:
echo "
<script type='text/javascript'>
loadAndShowImage(" . json_encode($imgData) . ", " . json_encode($i_gall) . ");
</script>";
Not sure what the problem is other than it's one of the characters in the full variable?:
var imgData = 'http://www.domain.com/_image.php/".$r_gall['image']."?width=145&height=205&cropratio=145:205&image=/images_cms/".$r_gall['image']."';
But I kept as much of the string in JS and just replaced the dynamic parts with PHP
hy, i have a php array with the name of some images!
i list all the images use this:
$files = $_SESSION['files'];
$imgid = $_POST['id'];
if ($files){
foreach($files as $image ):
print '<li id="liupimages">'."\n";
print '<img id="'.$imgid.'" alt="'.$image.'" src="uploads/'.$image.'">'."\n";
print "</li>\n";
endforeach;
print <<<JS
<script>
$(".thumbs li a").click(function(){
var largePath = $(this).attr("href");
$('.thumbs li').removeClass('thumbac');
$(this).parent().addClass('thumbac');
$("#largeImg").hide()
.attr({ src: largePath })
.load(function() {
$(this).show();
});
return false;
});
</script>
JS;
}
i use jquery-ui to drag and drop images using this function:
$(function() {
$("#upimagesQueue").sortable({ opacity: 0.6, cursor: 'move', update: function() {
//??
}
});
});
after i drag and drop one image i want to be able to update the php array to!
how to do this?
Use ajax:
$.get("re-arrange.php", { 'myArray[]': ['file1', 'file2']} );
http://api.jquery.com/jQuery.get/
Don't use jQuery use dom-drag it's much better and more functional.
Add this code:
<script type="text/javascript" src="http://www.dynamicdrive.com/dynamicindex11/domdrag/dom-drag.js"></script>
<script type="text/javascript">
Drag.init(document.getElementById("exampleid")); //sets the id to look for to make object draggable
</script>