HTML Background changes to current image - javascript

I am relatively new to coding. I downloaded a html template that is a timeline that I want to use for a project I am busy with. I am not using this as a website or to sell it or anything it is merely educational. I know how to edit the html and change it to my own words and add images etc. My problem is, I think, with the javascript. So what happens is,when you scroll on the timeline and it gets to an image the background changes to the active image and so it changes to every different image on the timestamps.
When i add new html code to essentially add more timestamps to the timeline the new timestamps image does not appear as the background. It seems as if it has a set length. I am completely clueless when it comes to javascript and would really appreciate it if someone could assist me with this. Here is the js file:
(function($) {
$.fn.timeline = function() {
var selectors = {
id: $(this),
item: $(this).find(".timeline-item"),
activeClass: "timeline-item--active",
img: ".timeline__img"
};
selectors.item.eq(0).addClass(selectors.activeClass);
selectors.id.css("background-image", "url(" + selectors.item.first().find(selectors.img).attr("src") + ")");
var itemLength = selectors.item.length;
$(window).scroll(function() {
var max, min;
var pos = $(this).scrollTop();
selectors.item.each(function(i) {
min = $(this).offset().top;
max = ($(this).height() + $(this).offset().top);
var that = $(this)
if (i == itemLength - 2 && pos > min + $(this).height() / 2) {
selectors.item.removeClass(selectors.activeClass);
selectors.id.css("background-image", "url(" + selectors.item.last().find(selectors.img).attr('src') + ")");
selectors.item.last().addClass(selectors.activeClass)
} else if (pos <= max - 40 && pos >= min) {
selectors.id.css("background-image", "url(" + $(this).find(selectors.img).attr('src') + ")");
selectors.item.removeClass(selectors.activeClass);
$(this).addClass(selectors.activeClass);
}
});
});
}
})(jQuery);
$("#timeline-1").timeline();
The HTML:
<div class="timeline-item" data-text="Text">
<div class="timeline__content"><img class="timeline__img" src="BG1.jpg"/>
<h2 class="timeline__content-title">
7 October 9:53 PM</h2>
<p class="timeline__content-desc">Text</p>
</div>
</div>

Related

Opening Div at a specific position

I need to open a div at a specific location on the page. When I focus on a textbox the div should be opened(made visible). I am able to do this part. The problem is it opens right underneath the textbox and when there is no scroll on the page, it creates one. I need help in showing the div above the textbox when there is more space on upper half of the page then the lower half of the page. Here is the JSFiddle I have created and if someone can edit it, it would be of too much help to me.
And this is how I am opening the div:
function openDIV(activatorCtl) {
var leftpos = 0;
var toppos = 0;
var sScrollTop = getScrollTop;
var aTag = activatorCtl;
do {
aTag = aTag.offsetParent;
sScrollTop = (aTag.scrollTop > sScrollTop) ? aTag.scrollTop : sScrollTop;
leftpos += aTag.offsetLeft;
toppos += aTag.offsetTop;
} while (aTag.tagName != 'BODY');
document.getElementById("divDetails").style.left = leftpos + "px";
document.getElementById("divDetails").style.top = toppos + 20 + "px";
document.getElementById("divDetails").style.zIndex = "999";
document.getElementById("divDetails").style.visibility = "visible";
}
You mean like this?
https://jsfiddle.net/36vdoaqo/3/
I added an if for when the toppos is bigger than 250 (your divs height)
if(toppos <= 250)
Another tip:
You use this 4 times in a row:
document.getElementById("divDetails")
save this element in an variable to get shorter statements like:
var detailsDiv = document.getElementById("divDetails");
detailsDiv.style.left = leftpos + "px";
detailsDiv.style.zIndex = "999";
EDIT: i did not save the jsfiddle properly.

I am creating multiple sliders in a page... but not getting the correct stop position if the number of slides are different from each other

I am creating multiple sliders in a page... but not getting the correct stop position if the number of slides are different from each other..
If I keep the number of slides same it works well..
But I need different number of slides in sliders...
$(document).ready(function(){
$('.myslider-wrapper').each(function(){
// thumbSlide
var countSlider = $('.thumbSlide').length;
if((".thumbSlide").length){
// Declare variables
var totalImages = $(".thumbSlide > li").length,
imageWidth = $(".thumbSlide > li:first").outerWidth(true),
totalWidth = imageWidth * totalImages,
visibleImages = Math.round($(".thumbSlide-wrap").width() / imageWidth),
visibleWidth = visibleImages * imageWidth,
stopPosition = (visibleWidth - totalWidth/countSlider);
$(".thumbSlide").width(totalWidth+10);
$(".thumbSlide-prev").click(function(){
var parentMove = $(this).parent().prev('.thumbSlide');
if(parentMove.position().left < 0 && !$(".thumbSlide").is(":animated")){
parentMove.animate({left : "+=" + imageWidth + "px"});
}
return false;
});
$(".thumbSlide-next").click(function(){
var parentMove = $(this).parent().prev('.thumbSlide');
if(parentMove.position().left > stopPosition && !$(".thumbSlide").is(":animated")){
parentMove.animate({left : "-=" + imageWidth + "px"});
}
return false;
});
}
});
});
here is jsFiddle URL:
http://jsfiddle.net/mufeedahmad/GLSqS/
You iterate through all sliders correctly by doing $('.myslider-wrapper').each(), but then you do some stuff with $('.thumbSlide') that should be $('.thumbSlide', this).
$('.thumbSlide') will select all elements on the page with that class, while $('.thumbSlide', this) within the each callback will only select the element in that particular wrapper.
Edit: fixed your jsfiddle with this solution: http://jsfiddle.net/GLSqS/1/

Getting Javascript/jQuery scrolling function to work on successive divs

I'm currently trying to implement functionality similar to infinite/continuous/bottomless scrolling, but am coming up with my own approach (as an intern, my boss wants to see what I can come up with on my own). So far, I have divs of a fixed size that populate the page, and as the user scrolls, each div will be populated with an image. As of now, the function I've written works on the first div, but no longer works on successive divs.
$(window).scroll(function () {
var windowOffset = $(this).scrollTop();
var windowHeight = $(this).height();
var totalHeight = $(document).height();
var bottomOffset = $(window).scrollTop() + $(window).height();
var contentLoadTriggered = new Boolean();
var nextImageCount = parseInt($("#nextImageCount").attr("value"));
var totalCount = #ViewBag.totalCount;
var loadedPageIndex = parseInt($("#loadedPageIndex").attr("value"));
var calcScroll = totalHeight - windowOffset - windowHeight;
$("#message").html(calcScroll);
contentLoadTriggered = false;
if (bottomOffset >= ($(".patentPageNew[id='" + loadedPageIndex + "']").offset().top - 1000)
&& bottomOffset <= $(".patentPageNew[id='" + loadedPageIndex + "']").offset().top && contentLoadTriggered == false
&& loadedPageIndex == $(".patentPageNew").attr("id"))
{
contentLoadTriggered = true;
$("#message").html("Loading new images");
loadImages(loadedPageIndex, nextImageCount);
}
});
This is the image-loading function:
function loadImages(loadedPageIndex, nextImageCount) {
var index = loadedPageIndex;
for(var i = 0; i < nextImageCount; i++)
{
window.setTimeout(function () {
$(".patentPageNew[id='" + index + "']").html("<img src='/Patent/GetPatentImage/#Model.Id?pageIndex=" + index + "' />");
index++;
var setValue = index;
$("#loadedPageIndex").attr("value", setValue);
}, 2000);
}
}
I was wondering what may be causing the function to stop working after the first div, or if there might be a better approach to what I'm attempting?
EDIT: It seems that loadedPageIndex == $(".patentPageNew").attr("id") within the if statement was the culprit.
#ViewBag.totalCount; is not a JavaScript, it's .NET, so your script probably stops after encountering an error.
Also: ".patentPageNew[id='" + loadedPageIndex + "']" is inefficient. Since IDs must be unique, just query by ID instead of by class name then by ID.

IE7-8 ignoring selectively ignoring jquery image .load() and/or contents of .load function

I'm writing a rather complex AJAX driven menu with multiple levels that animate around allowing a user to navigate a complicated tree structure at some point I had to add a function that auto centers (vert and horz) the images associated with each item on the menu tree. In order to measure the images and position them accordingly I must first write them to a hidden div ("#tempHolder") once they .load() I can then get their dimensions, calculate my offsets and then write the images to the DOM in the appropriate place.
This all works A Okay in the standards compliant browsers but IE7-8 seem to only process the .load() command when they feel like it. (homepage the menu loads okay, first visit to a sub-page breaks the menu, refreshing said page fixes it again...etc.). I restructured my function to make the .load() declaration early because of the advice I read here (http://blog.stchur.com/2008/02/26/ie-quirk-with-onload-event-for-img-elements/) but that doesn't seem to have worked. I also added e.preventDefault because of a stackOverflow thread that said this might prevent IE from caching my load statements.
Here is the function causing the issues:
if (this.imagePath != "") {
runImage = function (imagePath, $itemEle) {
var $itemEleA = $itemEle.find('a');
var image = new Image();
//$thisImage = $(image);
$(image).load(function (e) {
//alert('image loaded')
$(image).evenIfHidden(function (element) {
//alert('even if hidden');
////////////console.log($thisImage);
var elementWidth = element.width();
var elementHeight = element.height();
this.imageHeight = elementHeight;
this.imageWidth = elementWidth;
//alert('widthoffset = ' + widthOffset + 'imagewidth = ' + imageWidth + 'this.imageWidth = ' + this.imageWidth + 'elementWidth = ' + elementWidth);
var imagePaddingWidth = 230 - imageWidth;
var widthOffset = imagePaddingWidth / 2;
widthOffset = widthOffset + "px";
element.css("left", widthOffset);
var imagePaddingHeight = 112 - imageHeight;
if (imagePaddingHeight < 0) {
var heightOffset = imagePaddingHeight;
heightOffset = heightOffset + "px";
element.css("top", heightOffset);
}
if (imagePaddingHeight > 0) {
var heightOffset = imagePaddingHeight - 18;
heightOffset = heightOffset + "px";
element.css("top", heightOffset);
}
});
$(this).appendTo($itemEleA);
e.preventDefault();
return image;
});
image.src = imagePath;
//var tempvar = $itemEle.find('a');
$(image).appendTo("#tempHolder");
}
this.image = runImage(this.imagePath, $itemEle);
}
Since this is for a big client and the site is not yet live I can't show the site but I'll try to throw up some screen shots later.
Any help is greatly appreciated.
It is quite a common problem, and if the images are already in the cache some browsers (shall I say directly - IE?) fails to trigger load events on them. Hence there is a technique for a workaround.
// After this line of your code
image.src = imagePath;
// put this
if (image.complete || image.naturalWidth > 0) { // if image already loaded
$(image).load(); // trigger event manually
}

Javascript-moving image

How is it posible move an image from one position to other with fadeout?
I hav such functions
for hiding:
function SetOpacity(object,opacityPct)
{
// IE.
object.style.filter = 'alpha(opacity=' + opacityPct + ')';
// Old mozilla and firefox
object.style.MozOpacity = opacityPct/100;
// Everything else.
object.style.opacity = opacityPct/100;
}
function ChangeOpacity(id,msDuration,msStart,fromO,toO)
{
var element=document.getElementById(id);
var opacity = element.style.opacity * 100;
var msNow = (new Date()).getTime();
opacity = fromO + (toO - fromO) * (msNow - msStart) / msDuration;
if (opacity<0)
SetOpacity(element,0)
else if (opacity>100)
SetOpacity(element,100)
else
{
SetOpacity(element,opacity);
element.timer = window.setTimeout("ChangeOpacity('" + id + "'," + msDuration + "," + msStart + "," + fromO + "," + toO + ")",1);
}
}
function FadeOut(id)
{
var element=document.getElementById(id);
if (element.timer) window.clearTimeout(element.timer);
var startMS = (new Date()).getTime();
element.timer = window.setTimeout("ChangeOpacity('" + id + "',500," + startMS + ",100,0)",1);
}
for get current position or next position (by id of image and id of div)
function findPos(e){
var obj = document.getElementById(e);
var posX = obj.offsetLeft;var posY = obj.offsetTop;
while(obj.offsetParent){
posX=posX+obj.offsetParent.offsetLeft;
posY=posY+obj.offsetParent.offsetTop;
if(obj==document.getElementsByTagName('body')[0]){break}
else{obj=obj.offsetParent;}
}
alert(posX+'-'+posY);
}
the first position is position of image, and next - is position of div
The easiest approach with minimal code will be to use jQuery and use the animate function mate.
Ex:
$(".block").animate({"left": "+=50px"}, "slow");
You can use multiple parameters in the brackets like background-color, opacity, etc as you wish to dynamically change the values.
A link for your reference is located at: http://api.jquery.com/animate/
Most javascript animations rely on timer to create the effect of fluid motion. To slide an image across the page, you would set an interval that changed the css position to the right 1px every 5 milliseconds or something of the like. Javascript animation tutorial.
However, animation is most easily accomplished with a library like jquery or many others.

Categories

Resources