Tumblr jQuery - code not executing (NOT Masonry / Infinite scroll) - javascript

So, I was helping a friend develop a theme for her tumblr. As every reasonable web dev would do, I first developed it locally on my harddrive, putting in filler images. On my local copy, everything works fine. When I port it to a tumblr theme, a portion of the jQuery code ceases to function.
I'm using jQuery 2.0.3, and have MixItUp working, and a lightbox-esque function I wrote.
Here's the bit in question:
jQuery/javascript
$(window).load(function() {
$('.mix').on('click', function() {
var source = $(this).find('img').attr('src');
var image = $('<img src='+source+'>');
$('.overlay').children().remove();
$('.overlay').append(image);
$('.overlay').find('img').load(function() {
var overlayWidth = $('.overlay').width();
var overlayHeight = $('.overlay').height();
var overlayWPadding = overlayWidth - 40;
var imageWidth = $('.overlay').find('img').width();
var imageHeight = $('.overlay').find('img').height();
if (imageWidth > overlayWidth) {
var ratio = imageWidth / imageHeight;
var adjustedHeight = overlayWPadding / ratio;
var marginValue = (overlayHeight - adjustedHeight) / 2;
var marginTop = marginValue + "px";
$('.overlay').find('img').width(overlayWPadding);
$('.overlay').find('img').height(adjustedHeight);
$('.overlay').find('img').css('margin', ''+marginTop+' auto');
}
});
$('.overlay').css({'left': '200px', 'display': 'none'}).fadeIn(1000);
});
$('.overlay').on('click', function() {
$(this).fadeOut(500);
});
});
The HTML it affects:
<div id="Grid">
<div class="mix">
<img src="img/02.jpg" />
</div>
...
</div>
The respective tumblr code for it:
<div id="Grid">
{block:Posts}
<div class="mix" id="{PostID}">
{block:Photo}
<img src="{PhotoURL-HighRes}" />
{/block:Photo}
</div>
{/block:Posts}
</div>
The problem is that the function doesn't add the .overlay div when an image is clicked. Like I said, this works fine when I coded it locally, but when I load this into tumblr, it doesn't work. What's wrong and how do I fix it?
I don't think the CSS is the problem, but I'll put up any requested CSS.
Edit:

The issue is because there is no div like <div class="overlay"></div> in the given Tumblr page.
The lightbox is working fine when I added the below code.
<div class="overlay"></div>

Try use createElement() or appendTo() a div.overlay right after declare var image.

Related

TypeError, is not a function in Rails app [duplicate]

This question already has an answer here:
How to change image with fading
(1 answer)
Closed 3 years ago.
I'm quite new to js and jquery and I'm trying to do something very simple for my Rails app: I want to switch between 2 images every 3 seoncs with a fading effect. The problem is that I'm obtaining an error but don't know how to solve it (it's a typical error from what I've read but I had no luck in fixing it). I tested my code with jsfiddle and it works fine but when I run my app I get this error in the web console:
TypeError: $("#img").fadeOut is not a function.
Here is my code:
HTML code
<div class="container p-5">
<div class="row">
<div class="col">
<h2 class="display-5 mb-4">Title here</h2>
<p class="lead">Lead</p>
</div>
<div class="col">
<img id="img" src="http://localhost:3000/images/pdf_template.png" />
</div>
</div>
</div>
jquery code
<script type = "text/javascript">
var images = [];
images[0] = "http://localhost:3000/images/pdf_template.png";
images[1] = "http://localhost:3000/images/watermark_template.png";
var x = 0;
setInterval(displayNextImage, 3000);
function displayNextImage() {
x = x < images.length - 1 ? x : 0;
$("#img").fadeOut(300, function(){
$(this).attr('src', images[x]).fadeIn(300);
})
x++;
}
</script>
As I said, the code is working in a jsfiddle, so I suspect the problem is coming from my rails app but I didn't find anything relevant on google about it. The jquery code is located in my application.html.erb, in the head of the file. I managed to make some other jquery code works (an automatic image change but without fade effect) without any issue but this won't work.
I'm using Rails 5.2.3, jquery-rails 4.3.5, jquery 3.2.1
Any help would be appreciated, thanks.
I'm answering my own question here. #dbugger pointed out that it was a good practice to wrap functions in jquery in a document ready block. So here it is if anyone needs it:
jquery code
jQuery( document ).ready(function( $ ) {
var images = [];
images[0] = "http://localhost:3000/images/pdf_template.png";
images[1] = "http://localhost:3000/images/watermark_template.png";
var x = 0;
setInterval(displayNextImage, 3000);
function displayNextImage() {
x = x < images.length - 1 ? x : 0;
$("#img").fadeOut(300, function(){
$(this).attr('src', images[x]).fadeIn(300);
})
x++;
}
});
As you can see, the only change here is the addition of the jQuery( document ).ready(function( $ ) {}); block.

jquery to find img size and set to div css height and width

I am trying to get jquery to find the size of each image (between 8-10 images per page) in an owl carousel. For some reason, in the developer I just get back width 0px, height: 0px
here are the elements as they appear from developer:
<div class="item" style="width: 0px; height: 0px;">
<img src="url.com/img.jpg" alt="">
</div>
my jquery:
$('.item').each(function() {
var $this = $(this),
w = $this.find('img').width(),
h = $this.find('img').height();
$this.width(w).height(h);
});
how can i manage jquery to get the size of the image as it loads?
You need to fire your script after all the DOM elements are loaded. That is a good practice as well. Since you are using jQuery, just use the .ready() event to fire the script.
Fiddle Here
Code snippet follows,
$(document).ready(function() {
$('.item').each(function() {
var $this = $(this),
pic = $this.find('img');
if (pic.load) {
var w = pic.width();
var h = pic.height();
$this.width(w).height(h);
} else {
return;
}
});
alert("width : " + $('.item').width() + " & height : " + $('.item').height());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="item" style="width: 0px; height: 0px;">
<img src="http://dummyimage.com/190x100/000/fff.png
" alt="" />
</div>
Hope this helps. Happy Coding :)
UPDATE::
Another updated fiddle here
This time i added a dummy div element and gave that div the height and width of the item div.
Update #2:: You need to wait until atleast the image to load before you can run the script that finds out the height and width of the image and applies it to the parent div which in your case is the "item" div. So in case you want to run the script when the image is ready in the DOM tree but dont want to wait for the entire document DOM tree to be ready, then you can use jQuery .on("DOMready",".item img",function(){}); event function to achieve. I think this is more or less like lazy-load of images
Another update:: Updated my answer taking into account that the image may not be loaded when DOM is ready as per reference of these jQuery .ready() and .load() APIs.
You need to wait till the image is loaded before you query for its height and width.
Code snippet follows,
$(document).ready(function() { /* Just added this part */
$('.item').each(function() {
var $this = $(this),
$img = $this.find('img');
$img.load(function(){
var w = $this.find('img').width();
var h = $this.find('img').height();
alert("width: " + w + " & height: " + h);
$this.width(w).height(h)
});
;
});
}); /* Just added this part */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="item" style="width: 0px; height: 0px;">
<img src="http://dummyimage.com/190x100/000/fff.png
" alt="" />
</div>
Jquery ready function fires after the dom is ready and not after making sure the image is loaded.https://api.jquery.com/ready/.
example: https://jsfiddle.net/pomfr960/
Try this:
$('.item').each(function () {
var $this = $(this);
var img = $this.find('img');
if(!img.length) return;
img[0].onload = function () {
var w = img.width(),
h = img.height();
$this.width(w).height(h);
}
});

Use $(window).scroll function to jump to divs on a page

Im trying to mimic the functionality of this site https://moto360.motorola.com/
When you scroll down on that page it just jumps to the next "screen" and if you scroll up it jumps back up.
My JS is here :
var currentDiv = "Home";
var latestScroll = 0;
var scrollable = true;
$(document).ready(function(){
$("#HomeLink").addClass("activeNav");
$(".navLink").click(function(){
$(".navLink").removeClass("activeNav");
$(this).addClass("activeNav");
var divID = $(this).attr("data-linkID");
scrollTo(divID);
});
$(window).scroll(function(){
console.log(scrollable);
if (scrollable==true){
var currentScroll = $(window).scrollTop();
if (currentScroll > latestScroll){
scrollable = false;
//downscroll
if(currentDiv!="About"){
var nextDiv = $("#"+currentDiv).next()[0];
var nextDivID = $(nextDiv).attr("id");
scrollTo(nextDivID);
}
}else{
scrollable = false;
//upscroll
if(currentDiv!="Home"){
var prevDiv = $("#"+currentDiv).prev()[0];
var prevDivID = $(prevDiv).attr("id");
scrollTo(prevDivID);
}
}
}
});
});
function scrollTo(divID){
currentDiv = divID;
var target = $("#"+divID);
$('html,body').animate({
scrollTop: target.offset().top
}, 500);
setTimeout(function() {
// Do something after 2 seconds
latestScroll = target.offset().top;
scrollable = true;
}, 2000);
}
My problem is that once it starts scrolling it jumps to the next screen but then when the jQuery animate is running it registers more scrolls and then just keeps jumping. I've tried adding the boolean scrollable and even a timeout when setting that back to true but it still will jump at least twice.
HTML :
<div id="screens">
<div class="screen" id="Home">
<div id="logo">ZEPPA</div>
</div>
<div class="screen" id="Video">
<iframe width="100%" height="100%" src="http://www.youtube.com/embed/XGSy3_Czz8k"></iframe>
</div>
<div class="screen" id="Info">INFO</div>
<div class="screen" id="About">ABOUT US</div>
</div>
Anyone have any ideas on how to fix this? I cannot seem to find a way to get it to only register the scrolling once and then reset itself nicely.
I have a fiddle here: http://jsfiddle.net/a1cpx2cf/
I would recommend you to make use of a tested plugin like fullPage.js rather than trying to reinvent the wheel.
Things will become more complicated when you start worrying about touch screen computers, mobile phones, kinetic scrolling (used in Apple laptops), transitions performance, fallback compatibility with old browsers, keyboard accessibility, changes in the URL for each section, useful URLs for returning users or specific linking etc.
Using a tested script will always make things easier and will save you many headaches.

Change image source folder for mobile version with javascript

Sorry I'm a newbie with JS and I've been having trouble with some JS I found here on stackoverflow. My situation is that I have a div with two images inside, and I want to change the source path of those images when the window is less than 480px. My code is this:
<div id="bigFoto">
<img src="img/photo1.jpg" alt="text for alt" id="photo1">
<img src="img/photo2.jpg" alt="text for alt" id="photo2">
</div>
And The current script I'm running is:
$(window).resize(function(){
var width = $(window).width();
if (width < 481) {
$("#bigFoto img#photo1").attr("src","img/mobile/photo1.jpg");
$("#bigFoto img#photo2").attr("src","img/mobile/photo2.jpg");
}
else{
$("#bigFoto img#photo1").attr("src","img/photo1.jpg");
$("#bigFoto img#photo2").attr("src","img/photo2.jpg");
}
});
This script is working right, but now let's say I want that div to have 20 images, my guess is that I would have to add every one of them in this script right?
The real question: is there a way to target all images instead and just add the /mobile part on the source path? ,since the filename remains the same.
Thanks so much for your help!
You can use jQuery's each function to loop through all the elements returned by a query
$(window).resize(function(){
var width = $(window).width();
if (width < 481) {
$("#bigFoto img").each(function(index){
var src = $(this).attr("src")
var photoName = src.substr(src.lastIndexOf("/"));
$(this).attr("src", "img/mobile/"+photoName)
})
}
else{
$("#bigFoto img").each(function(index){
var src = $(this).attr("src")
var photoName = src.substr(src.lastIndexOf("/"));
$(this).attr("src", "img/"+photoName)
})
}
});

Pre-load Next Image jQuery

I am creating a slideshow using nested li's:
<ul id="ss_images_set">
<li>
<img link="images/koala_1.jpg" />
<p class="img_caption">©Copyright</p>
<p class="img_author">John Merriam</p>
<p class="img_href">http://www.twitter.com</p>
<p class="img_hashtag">JohnMerriam</p>
</li>
I will be uploading new images daily to this slideshow, so there will be many images in the set (hundreds). There are so many pre-loaders out there that I am confused as to what to use to load only the next image.
The slideshow has an image pre-loader, but I don't think it works properly because the next images are clearly not cached (content below slideshow jumps up and down when going to next image).
Here is the pre-loader script:
function preload_images(){
var pre_image = curr_img - 1;
if(pre_image < 0) pre_image = (tot_elements-1);
var curr_obj = 0;
if(!$('#img_preloaded_'+pre_image).length > 0){
curr_obj = slideshow[pre_image];
$('body').append('<img src="'+curr_obj["img_url"]+'" id="img_preloaded_'+pre_image+'" class="preload_box" />');
}
var pre_image = curr_img + 1;
if(tot_elements==pre_image) pre_image = 0;
if(!$('#img_preloaded_'+pre_image).length > 0){
curr_obj = slideshow[pre_image];
$('body').append('<img src="'+curr_obj["img_url"]+'" id="img_preloaded_'+pre_image+'" class="preload_box" />');
}
I don't know why it's not caching. Is it written wrong? Is it in the wrong spot in the following fiddle?
Fiddle with JS: http://jsfiddle.net/doobada/9m9eq/
Current ex. of slideshow (content below jumps up and down): https://www.assembla.com/code/cfrepo/subversion/node/blob/trunk/index.html#image=JohnMerriam
Ok, jQuery is not my strong suite (taking the tuts+ courses now), but this shouldn't be taking me 3 weeks to figure out.
Thanks for your help.
var newImageUrl = 'someimage.png';
/* preload an image using jQuery: */
$('<img>').attr( {
src: newImageUrl
} ).load(function() {
/* image is loaded and could be used */
} );

Categories