script works in jsfiddle but not in site - javascript

I have seen others ask this question but I couldn't find an answer that worked for me.
I posted a question a while back and someone sent me this jsFiddle: http://jsfiddle.net/r043v/LgXQX/1/
It does exactly what I need it to and the site says it's perfectly valid, but it's not working when I paste it into my document. I read about the extra invisible characters it will add when you c+p so I used jslint and it said I had gotten rid of them, but it still isn't working.
Here is the code as it is in my page (I started from scratch after it didn't work the first time so that I would be sure nothing else in my code was messing it up)
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="style3.css">
<script type=”text/javascript” src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script>
$("#issues > li").click(function () {
var $img = $("#theimg");
var $li = $(this);
var newsrc = "";
newsrc = $li.data("img");
if (newsrc === undefined) newsrc = "issue" + $li.index() + ".jpg";
var loadstep = 0;
function endstep() { // end of preload or hide
if (++loadstep === 2) // if the preload is done and hide too, change src and show picture
$img.attr("src", newsrc).animate({
opacity: 1
});
}
// preload picture
var $tmpimg = $("<img/>", {
src: newsrc
}).on("load", endstep);
// hide container picture
$img.animate({
opacity: 0
}, endstep);
});
</script>
</head>
The css file only has what's in the jsFiddle and the body is copied and pasted from the html section in the fiddle. Any insight would be greatly appreciated!

You need to load the script in a $(document).ready() handler. Fiddle adds it for you. Hence it is working there.
$(document).ready(function () {
$("#issues > li").click(function () {
var $img = $("#theimg");
var $li = $(this);
var newsrc = "";
newsrc = $li.data("img");
if (newsrc === undefined) newsrc = "issue" + $li.index() + ".jpg";
var loadstep = 0;
function endstep() { // end of preload or hide
if (++loadstep === 2) // if the preload is done and hide too, change src and show picture
$img.attr("src", newsrc).animate({
opacity: 1
});
}
// preload picture
var $tmpimg = $("<img/>", {
src: newsrc
}).on("load", endstep);
// hide container picture
$img.animate({
opacity: 0
}, endstep);
});
});

Related

External Javascript Not Working in Firefox

I have just hit an odd problem with an external javascript file. It works perfectly in Edge and Chrome but not in Firefox (51.0.1).
I have a number of scripts at the bottom of the body of the page, like this
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="js/adblocker.js"></script>
<script>
$(document).ready(function() {
$('.dir_hotel').keyup(function(event) {
if (event.keyCode == 13) {
this.form.submit();
return false;
}
});
});
</script>
<?php if ($mobile_browser > 0) { ?>
<script>
/* MOBILE COLLAPSE MENU */
(function($) {
$.fn.collapsable = function(options) {
// iterate and reformat each matched element
return this.each(function() {
// cache this:
var obj = $(this);
var tree = obj.next('.nav');
obj.click(function(){
if( obj.is(':visible') ){tree.toggle();}
});
});
};
})(jQuery);
$(document).ready(function(){
$('.slide-trigger').collapsable();
$(".slide-trigger").click(function(){
$('.slide-trigger').html($('.slide-trigger').text() == 'Collapse MENU' ? 'MENU' : 'Collapse MENU');
});
});
</script>
<?php }?>
</body>
The adblocker.js file doesn't run. I've tried adding an alert as the first line of the .js file and the alert never appears. I've checked the console in the browser and that shows the file is not loading.
If I replace
<script src="js/adblocker.js"></script>
with
<script>
window.onload=function(){
var clientHeight = document.getElementById('travins').clientHeight;
if (clientHeight < 20) {
var node = document.getElementById("insnote");
node.innerHTML = "<a href='https://clkuk.tradedoubler.com/click?p=18211&a=1906311&g=232597' target='_blank'>Columbus Direct Travel Insurance</a>";
}
var clientHeight = document.getElementById('flights').clientHeight;
if (clientHeight < 50) {
var node = document.getElementById("flightnote");
node.innerHTML = "<a href='http://www.kqzyfj.com/click-7782323-11015988-1440520708000' target='_blank'>Skyscanner</a>";
}
var clientHeight = document.getElementById('carhire').clientHeight;
if (clientHeight < 20) {
var node = document.getElementById("hirenote");
node.innerHTML = "<a href='http://www.zestcarrental.com/click.php?adm=1018&adt=14' target='_blank'>Zest Car Rental</a>";
}
var clientHeight = document.getElementById('parking').clientHeight;
if (clientHeight < 20) {
var node = document.getElementById("parknote");
node.innerHTML = "<a href='https://clkuk.tradedoubler.com/click?p=20642&a=1906311&g=20842820' target='_blank'>Purple Parking</a>";
}
var clientHeight = document.getElementById('brittany').clientHeight;
if (clientHeight < 20) {
var node = document.getElementById("ferrynote");
node.innerHTML = "<a href='http://being.successfultogether.co.uk/click.asp?ref=731409&site=6792&type=b3&bnb=3' target='_blank'>Brittany Ferries</a>";
}
};
</script>
it works perfectly.
I've tried js/adblocker.js, /js/adblocker.js and mydomain.com/js/adblocker.js and that makes no difference. I've also double-checked that the file is actually uploaded, which it is. I must be doing something stupid, but what?
As Joe correctly suggested, the Adblock Plus extension was blocking the adblocker.js file. Changing the file name to blocker.js has solved the problem.
I have to say that I think this is a mighty crude way of filtering advertising, as there must be so many innocent ways that a file might have "ad" in the name. I'll be watching for this in future whenever my Firefox does something unexpected.
Try to put your JavaScript code between this codes
(function($) { // your code here })(jQuery); in JavaScript file. It work with me.

play/stop gif on click using javascript

I want a gif to play when clicked, and to stop when clicked again. I'm following this method: http://www.hongkiat.com/blog/on-click-animated-gif/
So far, I have:
HTML
<figure>
<img src="test.png" alt="Static Image" data-alt="test.gif"/>
</figure>
<script src="playGif.js" type="text/javascript"></script>
playGif.js
(function($) {
// retrieve gif
var getGif = function() {
var gif = [];
$('img').each(function() {
var data = $(this).data('alt');
gif.push(data);
});
return gif;
}
var gif = getGif();
// pre-load gif
var image = [];
$.each(gif, function(index) {
image[index] = new Image();
image[index].src = gif[index];
});
// swap on click
$('figure').on('click', function() {
var $this = $(this),
$index = $this.index(),
$img = $this.children('img'),
$imgSrc = $img.attr('src'),
$imgAlt = $img.attr('data-alt'),
$imgExt = $imgAlt.split('.');
if($imgExt[1] === 'gif') {
$img.attr('src', $img.data('alt')).attr('data-alt', $imgSrc);
} else {
$img.attr('src', $imgAlt).attr('data-alt', $img.data('alt'));
}
});
})(jQuery);
Instead of swapping the content of src and data-alt, this only puts data-alt into src, and data-alt remains the same.
The gif does play on click, but if clicked again it reloads the gif instead of reverting to the png (at least in Chrome and Firefox. IE just does nothing on further clicks).
So here is the finished jsfiddle: https://jsfiddle.net/2060cm1c/
It is a simple variable swapping problem:
a=1;b=2;
a=b;// now a=2
b=a;// a=2, b=a=2
To solve it, you need a temporary variable:
a=1;b=2;
temp=a;a=b;
b=temp;
Now solve the OP's problem:
var temp=$img.attr('src');
$img.attr('src', $imgAlt).attr('data-alt', temp);
So, the problem is as easy as swapping 2 variables. You don't need the if to check the extension.

Get images width on .load() doesn't work on all browsers except firefox

I post my question here because I haven't find an answer to my issue.
I load some image in JavaScript. Each of them are in its own div. And I want to get the width of the div.
this.biggerElmts.find('img').each(function(){
var div = $('<div/>', {'class': this.divMinPic}).appendTo(divMinPics);
var img = $('<img/>', {
'class': this.minPic,
alt:'Miniature '+$(this).attr("alt"),
src:this.urlPic($(this).attr("src"), this.minPicFolder)
}) // if image not found, we put de default file
.error(function(){console.log("error loading image");$(this).attr("src", this.minPicFolder + this.defaultMinPic);})
.load(function(){
console.info($(this).width());
})
.appendTo(div);});
My problem is that it works fine on Firefox, but it doesn't on all other browser.
Firefox return me 185 and each other return me 0.
If you had a jsfiddle of your code we may be able to look more specifically at what is happening. But to the best if my knowledge the onload event works fine in all browsers that I have tried, whether using pure javascript or jquery.
Here is another thread where jquery was used to do just what you are asking about.
I also have a couple of pure javascript demos on jsfiddle you can look at if you are interested.
Ok SO, here is some code to go with the links to jsfiddle
var display = document.getElementById("display"),
images = {
"F12berlinetta": "http://www.ferrari.com/Site_Collection_Image_115x55/f12_thumb_home_115x55.png",
"458 Spider": "http://www.ferrari.com/Site_Collection_Image_115x55/110823_458_spider_menu.png",
"FF": "http://www.ferrari.com/Site_Collection_Image_115x55/ff_thumb_home_115x55.png",
"458 Italia": "http://www.ferrari.com/Site_Collection_Image_115x55/458_italia_menu_1_dx_ok.png",
"Ferrari California": "http://www.ferrari.com/Site_Collection_Image_115x55/california_menu_3_sx.png"
},
keys = Object.keys(images),
loaded = 0,
menuWidth = 0,
noWaitWidth = 0;
function clickedIt(evt) {
alert("You chose the " + evt.target.title);
}
function onLoaded(evt) {
loaded += 1;
menuWidth += evt.target.offsetWidth;
evt.target.addEventListener("click", clickedIt, false);
if (loaded === keys.length) {
console.log("Waited load width", menuWidth);
}
}
keys.forEach(function (key, index) {
var newDiv = document.createElement("div"),
newImg = document.createElement("img");
newImg.id = "thumb" + index;
newImg.src = images[key];
noWaitWidth += newImg.offsetWidth;
newImg.title = key;
newImg.addEventListener("load", onLoaded, false);
newDiv.appendChild(newImg);
display.appendChild(newDiv);
});
console.log("Didn't wait load width", noWaitWidth);
Demo 1
Demo 2

Fading background images from an array

$('.pictures a').click(function () {
var path = "place/of/images";
var pics = ['pic1.JPG',
'pic2.JPG',
'pic3.JPG',
'pic4.JPG'];
var i = 0;
var numberOfPics = pics.length - 1;
var vaheta = setInterval(function () {
$('body').css({ backgroundImage: 'url(' + path + pics[i] + ')' });
if (i == numberOfPics) {
i = 0;
} else {
i++;
}
}, 3000);
return false;
});
This is the code that is currently just changing background images for me. Now I found a topic here where it says you have to load the pictures as etc and there was this fiddle, http://jsfiddle.net/RnqQL/1/, this one, that is exactly what I want to do, but I don't quite know how to combine these two (my code and the fiddle).
The images will actually later be loaded with JSON from the server depending on the id of the link the person clicked to get this slideshow, this is too overwhelming for me...
I created fiddle at http://jsfiddle.net/xMrp3/1/
You can modify and use. I try to explain what i did with comments.
$('.pictures a').click(function () {
var path = "http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/";
$("#wrap").empty(); // clear wrap div content
$.getJSON('/echo/json/', function (pics) { // get json data
var pics = ['s-1.jpg', 's-5.jpg', 's-3.jpg']; // i override json response for demo
$.each(pics, function(i, pic) { // loop through pics array
$('<img/>').attr('src', path + pic).appendTo($("#wrap")); // append all images to #wrap div
});
if (animTimeout == null) // if we didnt started anim yet
anim(); // start animation
});
return false;
});
var animTimeout = null;
function anim() {
$("#wrap img").first().appendTo('#wrap').fadeOut(500);
$("#wrap img").first().fadeIn(500);
animTimeout = setTimeout(anim, 700);
}
​

Select link right after the one i just clicked

also threw it up on jsbin: http://jsbin.com/ohazo/2
but the code on jsbin is the old code, so overlay_nextimg is overlay_content.click in the javascript on jsbin
Jquery lightbox, grab next link from the one we just clicked, take it's href, fade out the current image, and load in the next img.
Also, how would i go about keeping the overlay_content centered? when changing images, have it animate to the new position? i was gonna tackle that next, but i'm here so why not.
Jquery and Html, i've changed the overlay_content.click that we were using before to overlay_nextimg, to be less confusing.
Jquery:
$(function (){
$('a.lightbox').click(function() {
var imghref = $(this).attr("href");
loadImage(imghref);
alert(imghref)
return false;
});
$('.overlay_nextimg').click(function (){
var currlink = $("a[href='" + $(".overlay_content img").attr("src") + "']");
var nextlink = $(currlink).next(".lightbox");
var prevlink = $(currlink).prev(".lightbox");
alert(nextlink);
loadImage(nextlink);
});
$('.overlay_previmg').click(function (){
var currlink = $("a[href='" + $(".overlay_content img").attr("src") + "']");
var nextlink = $(currlink).next(".lightbox");
var prevlink = $(currlink).prev(".lightbox");
alert(prevlink);
loadImage(prevlink);
});
function loadImage(href, prevlink, nextlink) {
var currentImg = $('.overlay_content img');
var img = new Image();
var docHeight = $(document).height();
$('.overlay_content').delay(300).fadeIn(400);
$(".overlay_bg").height(docHeight).fadeIn(400, function(){
$(img).load(function () {
$(img).hide();
$('.overlay_content').html(img);
$(img).fadeIn('slow');
}).error(function () {
$('.overlay_content').html("you SUCK at Javascript")
}).attr('src', href);
})
}
$('.overlay_bg').click(function (){
$(this).fadeOut(300);
$(".overlay_content").fadeOut(300, function(){
$(this).html('');
});
});
});
HTML:
<div class="overlay_bg"></div>
<div class="overlay_content"></div>
<h1>links</h1>
Load a water color image.
Load a library book, yeah.
from the interweb.
internet image.
HUGE
Please add more of the code/HTML - Is $("overlay_content").click(...) the function you need to fix?
You can use the eq() selector to get the n-th a.lightbox on the page. But obviously you'll need to track what link you're currently on., i.e.
$("a.lightbox:eq(1)")
Or - using the src of the image currently being displayed, find out which link was clicked and move next from there, i.e.
$("a.lightbox[href='" + currentImg.attr("src") + "']").next()

Categories