.appendChild() appends into the end of div - javascript

I was making a booklet with plugin MOLESKINE NOTEBOOK WITH JQUERY BOOKLET, and I want to dynamically add pages to it, using JS.
Though, when I try to add a page, all the stuff that needs to be on separate pages after the title one, appears on the very first page. And the strangest thing here is that after several refreshings or clearing the cache, it all stands as it should.
So, here is the code of the book:
<div class="book_wrapper">
<a id="next_page_button"></a>
<a id="prev_page_button"></a>
<div id="loading" class="loading">Загрузка книги...</div>
<div id="mybook" style="display:none;">
<div class="b-load" id="book_itself">
<div>
<img src="https://helpunicorn.pythonanywhere.com/static/logo.png" style="border-radius: 10px;">
<h1>Книга добрых дел</h1>
<br>
<div style="text-align: center;">
<h2 id="user">Пользователь #</h2>
</div>
</div>
</div>
</div>
</div>
Every div is supposed to be a separate page.
This is the code of my JS function:
<script>
$.getJSON('https://helpunicorn.pythonanywhere.com/kdd-info/aadev151', function(data) {
document.getElementById('title').innerHTML += `${data[0].username} (${data[0].name})`
document.getElementById('user').innerHTML += data[0].username
if (data.length != 1) {
for (i = 1; i < data.length; i++) {
const div = document.createElement('div');
div.innerHTML = `
<h1>${data[i].name}</h1>
<p>${data[i].info}</p>
`;
document.getElementById('book_itself').appendChild(div);
}
} else {
document.getElementById('book_itself').innerHTML += `
<div>
<h1>Упс... Эта книга пока пуста...</h1>
<p>Узнайте, как заполнить её, на сайте</p>
<br>
<a href="http://helpunicorn.ru" target="_blank" class="article">
<cufon class="cufon cufon-canvas" alt="Article" style="width: 41px; height: 16px;">
<canvas width="55" height="21" style="width: 55px; height: 21px; top: -2px; left: -4px;">
</canvas>
<cufontext>HelpUnicorn</cufontext>
</cufon>
</a>
</div>
`
}
});
</script>
So, I believe the problem is not with the code but with the plugin, because, as I mentioned earlier, it just takes a refreshing or clearing cache. But I'm wondering what's the exact problem with it
Please, watch a video for a better understanding

Related

How can i make a different counter for each photo in js? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm having problems with counter in js, i've made 3 img tags with different id's, but having difficulties what to put in if statement for each counter? How can i see which photo has been clicked?
var count = 0;
function promptImg() {
var count1 = document.getElementById(test1)
var count2 = document.getElementById(test2)
var count3 = document.getElementById(test3)
}
<div id="flowers">
<div class="1">
<img id="test1" onclick="promptImg()" src="rosa-avon-crvena-ajevke-52-373-standard-1.png">
</div>
<div class="2">
<img id="test2" onclick="promptImg()" src="gerbera.jpg">
</div>
<div class="3">
<img id="test3" onclick="promptImg()" src="gipsofila.jpg">
</div>
</div>
If you want to know how to determine which image was clicked, make sure you pass this into the function assigned to the onclick attribute.
To keep track of click frequency, you can use object or a Set to store the associated count with the ID of the image.
const counter = { };
function promptImg(img) {
counter[img.id] = (counter[img.id] || 0) + 1;
console.log(JSON.stringify(counter));
}
body div {
display: flex;
flex-direction: row;
grid-column-gap: 1em;
align-content: center;
}
.as-console-wrapper { max-height: 2.667em !important; }
<div id="flowers">
<div class="1">
<img id="test1" onclick="promptImg(this)" src="http://placekitten.com/120/60" />
</div>
<div class="2">
<img id="test2" onclick="promptImg(this)" src="http://placekitten.com/150/75" />
</div>
<div class="3">
<img id="test3" onclick="promptImg(this)" src="http://placekitten.com/160/80" />
</div>
</div>
Or store the click as a data attribute using dataset.
const counter = { };
const displayClickFrequency = () =>
console.log(JSON.stringify([...document.querySelectorAll('img')]
.reduce((map, img) => ({
...map,
[img.id]: parseInt(img.dataset.clicked, 10) || 0
}), {})));
function promptImg(img) {
const previousValue = parseInt(img.dataset.clicked, 10) || 0;
img.dataset.clicked = previousValue + 1;
displayClickFrequency();
}
body div {
display: flex;
flex-direction: row;
grid-column-gap: 1em;
align-content: center;
}
.as-console-wrapper { max-height: 2.667em !important; }
<div id="flowers">
<div class="1">
<img id="test1" onclick="promptImg(this)" src="http://placekitten.com/120/60" />
</div>
<div class="2">
<img id="test2" onclick="promptImg(this)" src="http://placekitten.com/150/75" />
</div>
<div class="3">
<img id="test3" onclick="promptImg(this)" src="http://placekitten.com/160/80" />
</div>
</div>
You can do it by using an event listener and checking the id of its target element:
document.addEventListener("click", function(element) {
if (element.target.id === "test1") {
//do something
}
});
You can do that with one of there two options:
function promptImg() {
console.log(event.target);
}
[...document.querySelectorAll(".flowers-with-eventlistener img")].forEach(img => {
img.addEventListener("click", () => {
console.log(event.target)
})
})
img {
width: 100px;
height: 100px;
}
<div class="flowers-with-onclick">
<img onclick="promptImg()" src="rosa-avon-crvena-ajevke-52-373-standard-1.png" >
<img onclick="promptImg()" src="gerbera.jpg">
<img onclick="promptImg()" src="gipsofila.jpg">
</div>
<div class="flowers-with-eventlistener">
<img src="rosa-avon-crvena-ajevke-52-373-standard-1.png" >
<img src="gerbera.jpg">
<img src="gipsofila.jpg">
</div>
If you apply a class to all of the images, you can create an event listener to find out which one has been clicked.
You can test it yourself by using the snippet below and clicking the images. Hope this helped.
var images = document.querySelectorAll(".shared-class");
for (i = 0; i < images.length; i++) {
images[i].addEventListener("click", function() {
console.log(this)
})
}
<div>
<img src="#" id="test1" class="shared-class" />
<img src="#" id="test2" class="shared-class" />
<img src="#" id="test3" class="shared-class" />
</div>
You possibly wat to delegate your clicks to the container - in your case the flowers div
window.addEventListener("load", function() { // on page load
document.getElementById("flowers").addEventListener("click", function(e) { // on click in flowers
const tgt = e.target;
if (tgt.tagName === "IMG") {
console.log(tgt.id);
}
})
})
img { width: 200px; }
<div id="flowers">
<div class="1"> <img id="test1" src="https://pharmarosa.hr/galeria_ecomm/5413/rosa-avon-crvena-ajevke-52-373-standard-1.png" /> </div>
<div class="2"> <img id="test2" src="https://upload.wikimedia.org/wikipedia/commons/2/23/Azimut_Hotels_Red_Gerbera.JPG" /></div>
<div class="3"> <img id="test3" src="https://www.provenwinners.com/sites/provenwinners.com/files/imagecache/low-resolution/ifa_upload/gypsophila-festival-star-02.jpg" /> </div>
</div>
To notice when a user clicks an element (such as an image) on your webpage, you probably want to use the .addEventListener method on that element or one of its "ancestor" elements in the DOM.
Check out MDN's Event Listener page and see the verbose example in the snippet.
// Identifies some elements;
const
flowersContainer = document.getElementById("flowers"),
rosaImg = document.getElementById("rosa-img"),
gerberaImg = document.getElementById("gerbera-img"),
gipsofilaImg = document.getElementById("gipsofila-img"),
countersContainer = document.getElementById("counters");
// Calls `handleImageClicks` when the user clicks on flowersContainer
// (This "event delegation" lets us avoid adding a listener
// for each image, which matters more in larger programs)
flowersContainer.addEventListener("click", handleImageClicks);
// Defines `handleImageClicks`
function handleImageClicks(event){
// Listeners can access events, which have targets
const clickedThing = event.target;
// Calls `incrementCount` for the selected flower
if(clickedThing == rosaImg){ incrementCount("rosa"); }
else if(clickedThing == gerberaImg){ incrementCount("gerbera"); }
else if(clickedThing == gipsofilaImg){ incrementCount("gipsofila"); }
}
// Defines `incrementCount`
function incrementCount(flowerName){
const
// `.getElementsByClassName` returns a list of elements
// (even though there will be only one element in the list)
listOfMatchingElements = countersContainer.getElementsByClassName(flowerName),
myMatchingElement = listOfMatchingElements[0], // First element from list
currentString = myMatchingElement.innerHTML, // HTML values are strings
currentCount = parseInt(currentString), // Converts to number
newCount = currentCount + 1 || 1; // Adds 1 (Defaults to 1)
myMatchingElement.innerHTML = newCount; // Updates HTML
}
#flowers > div { font-size: 1.3em; padding: 10px 0; }
#flowers span{ border: 1px solid grey; }
#counters span{ font-weight: bold; }
<div id="flowers">
<div><span id="rosa-img">Picture of rosa</span></div>
<div><span id="gerbera-img">Picture of gerbera</span></div>
<div><span id="gipsofila-img">Picture of gipsofila</span></div>
</div>
<hr />
<div id=counters>
<div>User clicks on rosa: <span class="rosa"></span></div>
<div>User clicks on gerbera: <span class="gerbera"></span></div>
<div>User clicks on gipsofila: <span class="gipsofila"></span></div>
</div>
In your promptImg function if you use jquery, and you should, inside it add
var idClick=$(this).attr("id");
console.log("This link was clicked"+idClick);
and then you can easily IF it

Why does my slider go blank after reaching the end?

I'm having a two issues/problems with the following slide.
It is a "double slider", so, two simultaneous slider in body section.
First is that when i reach the last image (9-nth, cos that much both sliders contain), the second slider continues to work properly (sliding images infinitely) but the first one just get blank.
Or if i click on previous button on begining then second doesn't work and images disapear, while the first one work nicely. Can't figure it out why. I've tried changing the "id" in the HTML and styling it but nothing change.
Second is, that i finally need to make it more dynamic, so, to avoid hardcoding images in the HTML and to putt them in JS and somehow append them in the DOM, but don't know what exactlly to do; creating an array, or using the "createElement"?
And which logic could be usable to actually include them in the DOM and have the following slider(s), considering the provided code?
Since it's my just second slider which i'm making, i found it pretty much hard, so any help/hint/advice is welcomed.
P.S Must be in jQuery and plugins excluded, so please don't provide any plugins links.
Thank you in advance.
var slides = $('.slide');
slides.first().before(slides.last());
$('button').on('click', function() {
// Selecting the slides
slides = $('.slide');
// Selecting button
var button = $(this);
// Register active slide
var activeSlide = $('.active');
// Next function
if (button.attr('id') == 'next') {
slides.last().after(slides.first());
activeSlide.removeClass('active').next('.slide').addClass('active');
}
// Previous function
if (button.attr('id') == 'previous') {
slides.first().before(slides.last());
activeSlide.removeClass('active').prev('.slide').addClass('active');
}
});
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
.slider {
position: relative;
width: 100%;
height: 300px;
overflow: hidden;
}
.slide {
width: 100%;
height: 300px;
position: absolute;
transition: 0.6s ease;
transform: translate(-100%, 0);
}
.slide img {
width: 100%;
height: 300px;
}
.slide.active {
transform: translate(0, 0);
}
.slide.active~.slide {
transform: translate(100%, 0);
}
body {
text-align: center;
}
button {
margin-top: 20px;
border: none;
border-radius: 0;
background: aqua;
color: #333;
padding: 10px;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="slider">
<div class="slide active">
<img src="Assets/slider-image-1.jpg" alt="">
</div>
<div class="slide">
<img src="Assets/slider-image-2.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-3.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-4.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-5.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-6.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-7.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-8.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-9.jpg">
</div>
</div>
<div class="slider">
<div class="slide active">
<img src="Assets/slider-image-1.jpg" alt="">
</div>
<div class="slide">
<img src="Assets/slider-image-2.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-3.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-4.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-5.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-6.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-7.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-8.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-9.jpg">
</div>
</div>
<button id="previous"><img src="Assets/arrow-blue-left.png" alt=""></button>
<button id="next"><img src="Assets/arrow-blue-right.png" alt=""></button>
Your code doesn't work properly because the slides = $('.slide') variable contains all slides from both sliders. You have to manipulate the slides in the to sliders independently. The second failure is that in your example the first slide is the initial active slide. Only slides in range second -> penultimate are allowed. Working example here
function handleSlide(slider, direction) {
var slides = $(slider).find('.slide');
if(slides.length < 1) return;
// Register active slide
var activeSlide = $(slider).find('.active');
// Next function
if (direction == 'next') {
slides.last().after(slides.first());
activeSlide.removeClass('active').next('.slide').addClass('active');
}
// Previous function
if (direction == 'previous') {
slides.first().before(slides.last());
activeSlide.removeClass('active').prev('.slide').addClass('active');
}
}
$('button').on('click', function() {
var button = $(this);
handleSlide($("#slider1"), $(button).attr('id'));
handleSlide($("#slider2"), $(button).attr('id'));
});
Loading images dinamically: You can do that by defining an array which contains the images and you can append the images into the slider using the jQuery 'append' method. Working example on jsFiddle.
function fillSliders(slider, images) {
$(slider).empty();
for(var i = 0; i < images.length; i++) {
if(typeof images[i] == "string" && images[i] !== "") {
var active = (i == 1) ? " active" : "";
$(slider).append('<div class="slide'+active+'"><img src="'+images[i]+'"
alt="image-'+i+'" /></div>');
}
}
}
var images = ["image1.jpg", "image2.jpg","image3.jpg","image4.jpg"];
fillSliders($("#slider"), images);

How to save the details of range slider in the local storage?

I am replicating this webpage https://www.modsy.com/project/furniture and I wrote the code On every slide there will be changing of image and phrase like that there are three phrases and images now I want to store the image and phrase in the local storage what the user has finalized
My html code is:
<div class="image mt-3 mb-3" id="sliderImages">
<img src="../static/images/1.jpg" width="400" height="180">
<img src="../static/images/2.jpg" width="400" height="180">
<img src="../static/images/3.jpg" width="400" height="180">
</div><br>
<div class="rangeslider">
<input type="range" min="1" max="3" value="1" class="myslider" id="sliderRange">
<div id="sliderOutput">
<div class="container">
<div class="row mt-4">
<div class="col-4">
<h6 class="display-6">Starting From Scratch</h6>
<p> I'm designing the room </p>
</div>
<div class="col-4">
<h6 class="display-6">Somewhere in Between</h6>
<p>I'm designing around a few pieces I already own</p>
</div>
<div class="col-4">
<h6 class="display-6">Mostly Furnished</h6>
<p>I want to put the finishing touches on my room</p>
</div>
</div>
</div>
<div class="container">
<div class="row mt-4">
<div class="col-4">
<h6 class="display-6">Starting From Scratch</h6>
<p> I'm designing the room </p>
</div>
<div class="col-4">
<h6 class="display-6">Somewhere in Between</h6>
<p>I'm designing around a few pieces I already own</p>
</div>
<div class="col-4">
<h6 class="display-6">Mostly Furnished</h6>
<p>I want to put the finishing touches on my room</p>
</div>
</div>
</div>
<div class="container">
<div class="row mt-4">
<div class="col-4">
<h6 class="display-6">Starting From Scratch</h6>
<p> I'm designing the room </p>
</div>
<div class="col-4">
<h6 class="display-6">Somewhere in Between</h6>
<p>I'm designing around a few pieces I already own</p>
</div>
<div class="col-4">
<h6 class="display-6">Mostly Furnished</h6>
<p>I want to put the finishing touches on my room</p>
</div>
</div>
</div>
</div>
<div class="row mb-3 mt-3">
<div class="col-4 mr-5">
« Home
</div>
<div class="col-4 ml-5">
Next » </div>
</div>
</div>
My CSS code is:
<style>
.rangeslider {
width: 50%;
margin: 0 auto;
position: absolute;
}
.myslider {
-webkit-appearance: none;
background: white;
width: 100%;
height: 20px;
opacity: 0.8;
margin-top: 180px;
}
.myslider::-webkit-slider-thumb {
-webkit-appearance: none;
cursor: pointer;
background: #000080;
width: 33%;
height: 20px;
}
.col-4 {
text-align: center;
}
.myslider:hover {
opacity: 1;
}
.image {
position: relative;
width: 400px;
margin: 0 auto;
}
.image>img {
position: absolute;
display: none;
}
.image>img.visible,
.image>img:first-child {
display: block;
}
#sliderOutput>div {
display: none;
}
#sliderOutput>div.visible,
#sliderOutput>div:first-child {
display: block;
}
#p1{
height: 10px;
}
</style>
My JS code is:
<script>
window.addEventListener('load', function() {
var rangeslider = document.getElementById("sliderRange");
var output = document.getElementById("sliderOutput");
var images = document.getElementById("sliderImages");
rangeslider.addEventListener('input', function() {
for (var i = 0; i < output.children.length; i++) {
output.children[i].style.display = 'none';
images.children[i].style.display = 'none';
}
i = Number(this.value) - 1;
output.children[i].style.display = 'block';
images.children[i].style.display = 'block';
});
});
</script>
My main requirement if the slider is in the first that phrase and image should be stored in local storage like that if it is in second that details should store.
There is no enough details about what json you want to store in the localStorage so that's why i am giving you the basic idea of how you can store a json in localStorage.
Basically you can't store json in localStorage directly but you can store that json in form of a stringand then converting that string(json) into json. Here is the basic example :
// setting json to localStorage
var jsonToBeStoredInLocalStorae = {
sliderImages = [
{path : 'image-path-here'},
{path : 'image-path-here'}
],
phrase : 'your image phrase'
};
localStorage.setItem('slider_json',JSON.stringify(jsonToBeStoredInLocalStorae ));
When you want to get that json from localStorage so you will do like this
//Here you are getting that json in `string` form from `localStorage` and parsing it to `json`
var localStorageJson = JSON.parse(localStorage.getItem('slider_json'));
In localStorage you can only save text strings, so if you want to save it is only one value per record, you insert a name and value to localStorage, but if you want to save an object, you must transform it to a text string with the function JSON.stringify

which element contains #id idString return index

Multiple elements with "column" class.
Find which column element contains a id: idString, return index of the !column! that contains the id
This is the new (3rd) html I am searching:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Style-Type" content="text/css">
<meta name="generator" content="Amazon.com">
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css" class="dontsplit"> .column *{ padding: 20px; }
</style>
</head>
<body class="calibre" style="margin: 0px; padding: 0px; width: 101024px;">
<div class="calibre67">
<div class="last first column" style="width: 616px; float: left;">
<p class="calibre2" style="padding-top: 8px; padding-bottom: 8px;">
<span class="calibre3">bla , bla etc.</span>
</p>
</div>
<div class="column" style="width: 616px; float: left;">
<div class="calibre1 split">
<p class="calibre2" style="padding-top: 8px; padding-bottom: 8px;">
<span class="calibre3">bla bla etc.</span>
</p>
</div>
</div>
<!-- div contains the ID I want to find, structure of page varies with different files -->
<div class="column" style="width: 616px; float: left;">
<div class="calibre1 split">
</p>
<p class="calibre4" style="padding-top: 8px; padding-bottom: 8px;">
<!-- This is the id I want to find, so the function should return 2 (3rd column). -->
<span id="1P-09761e033cf14df8aeccf069ebe7886e" class="calibre6">Prologue:</span>
</p>
<p class="calibre5" style="padding-top: 8px; padding-bottom: 8px;">
<span class="calibre6">It had been bla, bla etc.</span>
</p>
</div>
</div>
</div>
</body>
</html>
My Code:
var idString = "O-09761e033cf14df8aeccf069ebe7886e";
function findID(idString) {
$(".column").each(function(index, element){
if ($(this).find('*').attr('id') == idString) {
console.log(index);
return index;
}
});
return;
}
var result = findID(idString);
// should return/log 2
// currently returns/logs nothing
Function should return 2 in this example.
I have tried very many combinations of your suggestions.
What am I doing wrong?
if ($idString) will always return true. Instead of that check, you'll want to check against the .attr() of each element with if ($(this).attr('id') == idString).
Note that the attribute doesn't actually contain the #, so you'll want to remove the # from the ID variable, or make use of .contains().
This can be seen in the following:
var idString = "O-09761e033cf14df8aeccf069ebe7886e";
function findID(idString) {
$(".column").each(function(index, element) {
if ($(this).attr('id') == idString) {
console.log(index);
return index;
}
});
return;
}
findID(idString);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="column">“When the grav emitters are charged"</p>
<p class="column">“It wasn’t that bad this time”</p>
<p class="column" id="O-09761e033cf14df8aeccf069ebe7886e">Chapter 1</p>
<p class="column">“I can monitor engineering from up here”</p>
Also note that the index is zero-based.
You could use the jQuery .index(selector) method. It will return the index of the matched element (on the left hand side) within the collection of the selector on the right hand side.
A selector representing a jQuery collection in which to look for an element.
var idString = "#O-09761e033cf14df8aeccf069ebe7886e";
function findID(idToSearch) {
return $(idToSearch).index(".column p");
}
var result = findID(idString);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="column">
<p>“When the grav emitters are charged"</p>
</div>
<div class="column">
<p>“When the grav emitters are charged"</p>
</div>
<div class="column">
<p id="O-09761e033cf14df8aeccf069ebe7886e">Chapter 1</p>
<p>“I can monitor engineering from up here”</p>
</div>
<div class="column">
<p>“When the grav emitters are charged"</p>
</div>

Loading images asynchronously when in viewport in div with overflow: scroll;

I have this structure for my content:
<div id="content" style="overflow:scroll;height:500px; width: 500px;">
<div style="width:500px;height:100px;>
<img src='http://graph.facebook.com/user1/picture?width=50&height=50'>
</div>
<div style="width:500px;height:100px;>
<img src='http://graph.facebook.com/user2/picture?width=50&height=50'>
</div>
...
<div style="width:500px;height:100px;>
<img src='http://graph.facebook.com/userN/picture?width=50&height=50'>
</div>
</div>
So basically I have a div with overflow:scroll; which contains pictures of all the Facebook user's friends. For performance reasons, I think it's better to load images when they become visible in the viewport. I've tried everything including jquery.lazyload but I think because the images are inside my div with overflow:scroll the plugin doesn't function correctly.
I used this post to elaborate the following code.
First of all change your html to get image only from the first:
<div id="content" style="overflow:scroll;height:100px; width: 100px;">
<div style="width:500px;height:100px;">
<img src='http://graph.facebook.com/user1/picture?width=50&height=50' />
</div>
<div style="width:500px;height:100px;">
<img msrc='http://graph.facebook.com/user2/picture?width=50&height=50'/>
</div>
...
<div style="width:500px;height:100px;">
<img msrc='http://graph.facebook.com/userN/picture?width=50&height=50'/>
</div>
</div>
Then use this js to trigger scroll event from #content div and check if all the image is visible:
$(function(){
var content = $("#content");
function isScrolledIntoView(elem)
{
var divViewTop = content.scrollTop();
var divViewBottom = divViewTop + content.height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom <= divViewBottom) && (elemTop >= divViewTop));
}
content.scroll(function(e){
content.find("img").each(function(i,e){
if(isScrolledIntoView(e)){
$(e).attr("src",$(e).attr("msrc"));
}
});
});
});
Please don't use this in production, the code should be optimized first.
Here is a link to the jsfiddle:
If you think its because of the divs, why not remove them:
<div id="content" style="overflow:scroll;height:500px; width: 500px;">
<img height='100' width='500' src='http://graph.facebook.com/user1/picture?width=50&height=50'>
<img height='100' width='500' src='http://graph.facebook.com/user2/picture?width=50&height=50'>
...
</div>

Categories

Resources