OwlCarousel2 Updating URL Hash Navigation on Drag - javascript

I am currently using OwlCarousel2 for my carousel needs. I chose OwlCarousel2 over OwlCarousel1 since it has an URL hash navigation: http://www.owlcarousel.owlgraphic.com/demos/urlhashnav.html
<div id="contestant-carousel">
<div id="poll-images" class="owl-carousel">
<?php
for($counter = 1; $counter <= 14; $counter++) {
echo "<div class='item' data-hash='$counter'><a href='" . HTTP_SERVER . "vote.php?contestant_id=$counter'><img src='/images/contestants_mobile/$counter.png' alt='$counter'></a></div>";
}
?>
</div>
</div>
Above is the PHP code I use to generate my carousel. I have fourteen images, so my code loops through all fourteen images and adds a data-hash object to each image (for the anchor navigating needs).
The following is my Javascript code:
$(document).ready(function() {
$("#poll-images").owlCarousel({
items: 1,
loop:false,
center:true,
margin:10,
lazyLoad:false,
URLhashListener:true,
onDragged:callback,
autoplayHoverPause:true,
startPosition: 'URLHash'
});
function callback(event) {
window.location.hash = event.item.index;
console.log(event.item.index);
}
});
Now, the above carousel works perfectly if the user manually adds in the hash in their URL, i.e. someurl.com/voting.php#4, this would navigate to the fourth image.
However, want I want to do is, if the url navigates to someurl.com/voting.php, as they scroll through each image, my URL would update its anchor accordingly. Why? Since if my user clicks on the image (which contains a href), and they go to the previous page, they could navigate back to the image they were looking at, instead of the default behavior of going to the first image.
According to the OwlCarousel2 API (which is actually quite different from OwlCarousel1), to get the current item, you can do this:
function callback(event) {
// Provided by the core
var element = event.target; // DOM element, in this example .owl-carousel
var name = event.type; // Name of the event, in this example dragged
var namespace = event.namespace; // Namespace of the event, in this example owl.carousel
var items = event.item.count; // Number of items
var item = event.item.index; // Position of the current item
// Provided by the navigation plugin
var pages = event.page.count; // Number of pages
var page = event.page.index; // Position of the current page
var size = event.page.size; // Number of items per page }
Specifically, using event.item.index. My code did precisely that! But I am unable to retrieve the current index! My error is: Uncaught TypeError: Cannot read property 'item' of undefined under Chrome's console.
Any help from JS gurus would be much appreciated!
I tried searching all over StackOverflow as well as the OwlCarousel2 API to see if I could do this, however, no luck.
I have also checked this thread: append /remove anchor name from current url without refresh

Found the fix here!
// jQuery method on
owl.on('changed.owl.carousel', function(property){
var current = property.item.index;
window.location.hash = current + 1;
});
OwlCarousel2 guy needs to update his API =/
Found here: Owl Carousel 2 - Get src of current slide

Related

jQuery Hide/Show DIV on change of anchor text

I have one page website which changes URL #id or anchor text on scrolling and on navigation click. I have an image positioned fixed at the center of the site. The site is divided in different sections and the image shows in all the sections. I do not want to show the image on the first section as it is unrelated to the content of the 1st section but will be showed in all next sections. How can I make it work?
What I have tried till now but not working:
$(document).ready(function(){
$(".phone").hide();
var idSample = window.location.href.split("#");
var id = "#"+idSample[1];
if($(id) == "second"){
$(".phone").show();
}else{
$(".phone").hide();
}
});
Rest in Fiddle: https://jsfiddle.net/shubhamjha1000/vh7bu32q/
I don't want that phone to be seen on 1st section but on rest of the sections. Please help me guys!
You can use the answer written in this question to listen to changes in the window see what url you are on and show or hide the phone accordingly....
Example:
$(function(){
// Bind the event.
$(window).hashchange(hashchanged);
// Trigger the event (useful on page load).
hashchanged();
});
function hashchanged(){
var hash = location.hash.replace( /^#/, '' );
//your code
if(hash == "#first") {
// Hide element
} else {
// Show element
}
}
But still even though what you are planning to do will work with that solution I think it would still look bad on the app it self and instead of a hovering phone maybe you can create the phone as an img inside the relevant containers and hide and show with id...
You can simply use a substring on your location.hash for get your hash tag
$(document).ready(function(){
$(".phone").hide();
var id = window.location.hash.substr(1);
if($(id) == "second"){
$(".phone").show();
}else{
$(".phone").hide();
}
});

anchor href does not display properly

I am trying to navigate to another page section with anchor tag from current page /contact.html. The problem I am having here is that the result view do not correspond to the start of the container. Upon searching online, I suspect that it was because the web site components are dynamically loaded and do not have fixed height for the image slider.
Nonetheless, I did not find any solution to this problem yet. Hope someone can help me in this issue.
Note: The anchor tag work perfectly as it is if it is used in the index.html page itself.
For code reference and better illustrations, please refer to following link. This is exactly the problem I am facing.
Click here
Click here
Click here
As you said in comments, you have a fixed position on your header, so you need to calculate in JS your header height.
If you have jQuery:
$('a').on('click' function(){
var $link = $(location.href);
var position = $link.offset().top - $('#header').height()
$(window.animate({scrollTop: position},{duration: 500})
});
For onload with an anchor in the URL:
$(window).load(function() {
var $link = $(location.href);
if($link.length {
var position = $$link.offset().top - $('#header').height()
$(window.animate({scrollTop: position},{duration: 500})
}
});

How to scroll to a specifc element when there is already an # anchor on the url

I have a web site on based on SkelJS that currently loads a different part of the webpage by appending an #anchor to the url like this:
Note that #blog loads the blog page, the scroll is at the top. Inside the Blog page I need to scroll to a certain article. How can I use two anchors so that something like #blog#article_x would work? I suppose I have to look for a workaround since anchoring 2 ids makes no sense, is there a work around?
Additional notes:
Note that if a change #blog to #article_x it actually goes to the desired article however if someone shares the link it won't go to the article because it will look for #article_x on the homepage, where it does not exists.
Here is a demo of the template I'm using (http://html5up.net/uploads/demos/astral/#) note how the #anchor loads the desired page.
You can use a hash that contains both page and element. Then split and then do your page load then scroll, i.e. #blog,someelement
//on page load or wherever you detect the hash
$(function(){
var hash = window.location.hash;
var ele = null;
//Detect if there is a splitable hash
if(hash.indexOf(",") != -1){
var parts = hash.split(",");
hash = parts[0];
ele = jQuery("#"+parts[1]);
}
//whatever function you do to load the blog page
loadPage(hash,ele);
});
function loadPage(page,ele){
//do page loading
$("#page").load("http://someurl.com",function(){
//if there was no second part to the hash
//this will be skipped
if(ele){
$("html,body").animate({
scrollTop: ele.offset().top
},1000);
}
});
}
JSfiddle Demo
Considering the ID of the element that you want to scroll to is myelement you can use below jquery code to smoothly scroll to it.
$("html,body").animate({scrollTop : $("#myelement").offset().top},1000);
We can scroll to specific div when it has id or class
var $id=window.location.href.split('#')[1];
$('html, body').scrollTop($("#"+$id).offset().top)

Stuck: hide/show divs with next button, redirect last div

Here's what I have so far, which allows the user to click an image to open a new window and go to a location. When that click occurs, the image in the parent window is replaced with the next div.
Example: http://jsfiddle.net/rzTHw/
Here's the working code so far...
<div class = "box"><img src="http://placehold.it/300x150/cf5/&text=img+1"></div>
<div class = "box"><img src="http://placehold.it/300x150/f0f/&text=img+1"></div>
<div class = "box"><img src="http://placehold.it/300x150/fb1/&text=img+1"></div>
<div class = "box"><img src="http://placehold.it/300x150/444/&text=img+1"></div>​
Jquery:
$('.box').not(':first').hide();
$('.box a').click(
function(e){
e.preventDefault();
var newWin = window.open(this.href,'newWindow'),
that = $(this).closest('.box'),
duration = 1200;
if (that.next('.box').length){
that.fadeOut(duration,
function(){
that.next('.box').fadeIn(duration);
});
}
});
What I am having trouble with is:
Creating a "next" button so the user can cycle through to the next div without having the click the image, thus avoiding having to open a new window to get to the next image.
Having a click on the last div redirect the window location to a URL, while still doing the normal function of opening a new window to the a href location if the image is clicked. Otherwise if clicking the "next" button when the last div is shown, simply redirect the user.
What's the best way to go about this? Thanks!
Here is my attempt at tweaking your code to allow for a next button, and my best guess at what you want to happen for the last image:
var redirectUrl = 'http://www.google.com'; // replace in your code
function next(event, duration) {
duration = duration || 1200; // default value
var that = $('.box:visible');
if (that.next('.box').length) {
that.fadeOut(duration, function() {
that.next('.box').fadeIn(duration);
});
} else {
window.location.href = redirectUrl;
// the above line doesn't work inside jsFiddle, but should on your page
}
return false;
}
$('.box').not(':first').hide();
$('.box a').click(
function(e) {
e.preventDefault();
var newWin = window.open(this.href, 'newWindow'),
duration = 1200;
next(e, duration);
});
$('.next').click(next);
jsFiddle example here. Note the redirect is prevented in some browsers since it is running inside an iframe. But it should work in a normal page.
Perhaps look at a slideshow jquery plugin. JQuery Cycle being just one example. There are plenty. Just google jquery Slideshow or jquery cycle and pick the one that suites you best. The cycle plugin itself has a number of "pager" examples that let you change the contents of the displayed picture without leaving the page.
Most of them offer having the contents be html and not just a simple picture so you can play around with what exactly you want.
There's also Fancybox, lightbox, colorbox, etc. if that's what you're trying to accomplish.

Show jQuery cycle slide by using #hash/anchor, not numbers

I'm working on a one page layout site, where I use jQuery Cycle to switch between content.
Currently I've changed the script so it displays the current slide in the URL (to make it possible to Favorite the current slide).
I've also made it possible to Alert the right ID, but I can't get it to activate the slide-function/effect.
$(window).bind('hashchange', function () { //detect hash change
var hash = window.location.hash.slice(1); //hash to string (= "myanchor")
alert(hash); //This Alerts the right ID/anchor of the current slide
//$('.slideshow').cycle(hash); // This doesn't work. If I use 1, 2, 3 etc. it shows the diffent slides
});
How can I get this to work? Am I missing something?
Thank you in advance.
I have not done it yet, but am about to try out this solution: http://wesbos.com/jquery-cycle-link-within-hashchange/
Edit: works like a charm!

Categories

Resources