How to create link on image using Javascript - javascript

<div id="mydiv">
<img src="myimage.jpg" />
</div>
<script language="javascript">
var a=document.createElement('a');
a.href='http://mylink.com';
document.getElementById('mydiv').appendChild(a);
</script>
The script doesn't work to create link on image
<div id="mydiv">
<img src="myimage.jpg" />
</div>

You are putting the link after the image.
You need to move the image so it is inside the link.
var image = document.getElementById('mydiv').getElementsByTagName('img')[0];
a.appendChild(image);

<div id="mydiv">
<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/4/4d/Cat_November_2010-1a.jpg/220px-Cat_November_2010-1a.jpg" />
</div>
<script language="javascript">
var a=document.createElement('a');
a.href='http://mylink.com';
var image = document.getElementById('mydiv').getElementsByTagName('img')[0];
b=a.appendChild(image);
document.getElementById('mydiv').appendChild(a);
</script>
Thank's for the idea. this work

Here is a solution that doesn't need the additional div and puts a link around every image within the HTML page:
<!-- jQuery -->
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
<script type="text/javascript" charset="utf8">
$(document).ready(function(){
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
var image = images[i];
var parentElement = image.parentElement;
var a = document.createElement('a');
a.href = image.getAttribute('src');
a.appendChild(image);
parentElement.appendChild(a);
}
});
</script>

For single images
Where you can pass the image by element object, ID, or the first src substring match. Takes an optional target attribute, like "_blank". No jQuery required.
// By img element object
// (used by the functions below)
var addImageLink = function( elem, target ){
if( !elem || !( 'tagName' in elem ) ){ return; }
var image = elem;
var parent = image.parentElement;
var a = document.createElement( 'a' );
a.href = image.getAttribute( 'src' );
if( target ){ a.setAttribute( 'target', target ); }
a.appendChild( image );
parent.appendChild( a );
};
// By img element id
// <img src="images/gallery/1.jpg" id="image1" />
// <script> addImageLinkById( 'image1' ); </script>
var addImageLinkById = function( id, target ){
addImageLink( document.getElementById( id ), target );
};
// By img element src (first match)
// <img src="images/gallery/1.jpg"/>
// <script> addImageLinkBySrc( '/1.jpg' ); </script>
var addImageLinkBySrc = function( src, target ){
var image, images = document.getElementsByTagName( 'img' );
if( typeof src == 'undefined' ){ src = ''; }
for( var i = 0; i < images.length; i++ ){
if( images[ i ].src.indexOf( src ) < 0 ){ continue; }
addImageLink( images[ i ], target ); return;
}
};
For looping through all images
This solution puts a link around every image. It's an expanded version of Falko's answer.
Doesn't use jQuery
Optionally whitelist images by href substring, like "images/gallery/"
Specify an optional target attribute, like "_blank"
Won't skip the second half of the images(I experienced this issue when trying his code, but it could be something I did wrong)
var addImageLinks = function( filter, target ){
var parent, a, image;
var images = document.getElementsByTagName( 'img' );
var hasTarget = ( typeof target != 'undefined' );
var hasFilter = ( typeof filter != 'undefined' );
for( var i = 0; i < images.length; i++ ){
image = images[ i ];
if( hasFilter && ( image.src.indexOf( filter ) < 0 ) ){ continue; }
// Skip over already-wrapped images, by adding an attribute
if( image.getAttribute( 'data-wrapped-link' ) ){ continue; }
image.setAttribute( 'data-wrapped-link', '1' );
// Add the link
parent = image.parentElement;
a = document.createElement( 'a' );
a.href = image.getAttribute( 'src' );
if( hasTarget ){ a.setAttribute( 'target', target ); }
a.appendChild( image );
parent.appendChild( a );
// We inserted a "new" image, so go back one step so we don't miss any
// (due to being inside the "i < images.length" loop)
i--;
}
};
// Then:
// <img src="images/gallery/a.jpg"/>
// <img src="images/gallery/b.jpg"/>
// <img src="images/gallery/c.jpg"/>
// <img src="images/icons/a.gif"/> <- ignored
// Near bottom of the page (or in an onLoad handler, etc):
// </script> addImageLinks( 'images/gallery/', '_blank' ); </script>

Related

How to reload a page on slider navigation click

I've a problem with this slider: I want to make it slider reload the page after I'm clicking the link "next/prev" in the slider or hte thumbnail.
Can someone help me ?
$(function() {
// ======================= imagesLoaded Plugin ===============================
// https://github.com/desandro/imagesloaded
// $('#my-container').imagesLoaded(myFunction)
// execute a callback when all images have loaded.
// needed because .load() doesn't work on cached images
// callback function gets image collection as argument
// this is the container
// original: mit license. paul irish. 2010.
// contributors: Oren Solomianik, David DeSandro, Yiannis Chatzikonstantinou
$.fn.imagesLoaded = function( callback ) {
var $images = this.find('img'),
len = $images.length,
_this = this,
blank = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
function triggerCallback() {
callback.call( _this, $images );
}
function imgLoaded() {
if ( --len <= 0 && this.src !== blank ){
setTimeout( triggerCallback );
$images.off( 'load error', imgLoaded );
}
}
if ( !len ) {
triggerCallback();
}
$images.on( 'load error', imgLoaded ).each( function() {
// cached images don't fire load sometimes, so we reset src.
if (this.complete || this.complete === undefined){
var src = this.src;
// webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
// data uri bypasses webkit log warning (thx doug jones)
this.src = blank;
this.src = src;
}
});
return this;
};
// gallery container
var $rgGallery = $('#rg-gallery'),
// carousel container
$esCarousel = $rgGallery.find('div.es-carousel-wrapper'),
// the carousel items
$items = $esCarousel.find('ul > li'),
// total number of items
itemsCount = $items.length;
Gallery = (function() {
// index of the current item
var current = 0,
// mode : carousel || fullview
mode = 'carousel',
// control if one image is being loaded
anim = false,
init = function() {
// (not necessary) preloading the images here...
$items.add('<img src="images/ajax-loader.gif"/><img src="images/black.png"/>').imagesLoaded( function() {
// add options
_addViewModes();
// add large image wrapper
_addImageWrapper();
// show first image
_showImage( $items.eq( current ) );
});
// initialize the carousel
if( mode === 'carousel' )
_initCarousel();
},
_initCarousel = function() {
// we are using the elastislide plugin:
// http://tympanus.net/codrops/2011/09/12/elastislide-responsive-carousel/
$esCarousel.show().elastislide({
imageW : 65,
onClick : function( $item ) {
if( anim ) return false;
anim = true;
// on click show image
_showImage($item);
// change current
current = $item.index();
}
});
// set elastislide's current to current
$esCarousel.elastislide( 'setCurrent', current );
},
_addViewModes = function() {
// top right buttons: hide / show carousel
var $viewfull = $(''),
$viewthumbs = $('');
$rgGallery.prepend( $('<div class="rg-view"/>').append( $viewfull ).append( $viewthumbs ) );
$viewfull.on('click.rgGallery', function( event ) {
if( mode === 'carousel' )
$esCarousel.elastislide( 'destroy' );
$esCarousel.hide();
$viewfull.addClass('rg-view-selected');
$viewthumbs.removeClass('rg-view-selected');
mode = 'fullview';
return false;
});
$viewthumbs.on('click.rgGallery', function( event ) {
_initCarousel();
$viewthumbs.addClass('rg-view-selected');
$viewfull.removeClass('rg-view-selected');
mode = 'carousel';
return false;
});
if( mode === 'fullview' )
$viewfull.trigger('click');
},
_addImageWrapper= function() {
// adds the structure for the large image and the navigation buttons (if total items > 1)
// also initializes the navigation events
$('#img-wrapper-tmpl').tmpl( {itemsCount : itemsCount} ).prependTo( $rgGallery );
if( itemsCount > 1 ) {
// addNavigation
var $navPrev = $rgGallery.find('a.rg-image-nav-prev'),
$navNext = $rgGallery.find('a.rg-image-nav-next'),
$imgWrapper = $rgGallery.find('div.rg-image');
$navPrev.on('click.rgGallery', function( event ) {
_navigate( 'left' );
return false;
});
$navNext.on('click.rgGallery', function( event ) {
_navigate( 'right' );
return false;
});
// add touchwipe events on the large image wrapper
$imgWrapper.touchwipe({
wipeLeft : function() {
_navigate( 'right' );
},
wipeRight : function() {
_navigate( 'left' );
},
preventDefaultEvents: false
});
$(document).on('keyup.rgGallery', function( event ) {
if (event.keyCode == 39)
_navigate( 'right' );
else if (event.keyCode == 37)
_navigate( 'left' );
});
}
},
_navigate = function( dir ) {
// navigate through the large images
if( anim ) return false;
anim = true;
if( dir === 'right' ) {
if( current + 1 >= itemsCount )
current = 0;
else
++current;
}
else if( dir === 'left' ) {
if( current - 1 < 0 )
current = itemsCount - 1;
else
--current;
}
_showImage( $items.eq( current ) );
},
_showImage = function( $item ) {
// shows the large image that is associated to the $item
var $loader = $rgGallery.find('div.rg-loading').show();
$items.removeClass('selected');
$item.addClass('selected');
var $thumb = $item.find('img'),
largesrc = $thumb.data('large'),
title = $thumb.data('description');
$('<img/>').load( function() {
$rgGallery.find('div.rg-image').empty().append('<img src="' + largesrc + '"/>');
if( title )
$rgGallery.find('div.rg-caption').show().children('p').empty().text( title );
$loader.hide();
if( mode === 'carousel' ) {
$esCarousel.elastislide( 'reload' );
$esCarousel.elastislide( 'setCurrent', current );
}
anim = false;
}).attr( 'src', largesrc );
},
addItems = function( $new ) {
$esCarousel.find('ul').append($new);
$items = $items.add( $($new) );
itemsCount = $items.length;
$esCarousel.elastislide( 'add', $new );
};
return {
init : init,
addItems : addItems
};
})();
Gallery.init();
/*
Example to add more items to the gallery:
var $new = $('<li><img src="images/thumbs/1.jpg" data-large="images/1.jpg" alt="image01" data-description="From off a hill whose concave womb reworded" /></li>');
Gallery.addItems( $new );
*/
});
Here is the code for the view
<noscript>
<style>
.es-carousel ul{
display:block;
}
</style>
</noscript>
<script id="img-wrapper-tmpl" type="text/x-jquery-tmpl">
<div class="rg-image-wrapper">
{{if itemsCount > 1}}
<div class="rg-image-nav">
Previous Image
Next Image
</div>
{{/if}}
<div class="rg-image"></div>
<div class="rg-loading"></div>
<div class="rg-caption-wrapper">
<div class="rg-caption" style="display:none;">
<p></p>
</div>
</div>
</div>
</script>
</head>
<body>
<div class="container">
<div class="header">
<span>« Previous Demo: </span>Elastislide
<span class="right_ab">
Images by Shermeee
CC BY 2.0
<strong>back to the Codrops post</strong>
</span>
<div class="clr"></div>
</div><!-- header -->
<div class="content">
<h1>Responsive Image Gallery <span>A jQuery image gallery with a thumbnail carousel</span></h1>
<div id="rg-gallery" class="rg-gallery">
<div class="rg-thumbs">
<!-- Elastislide Carousel Thumbnail Viewer -->
<div class="es-carousel-wrapper">
<div class="es-nav">
<span class="es-nav-prev">Previous</span>
<span class="es-nav-next">Next</span>
</div>
<div class="es-carousel">
<ul>
<li><img src="images/thumbs/1.jpg" data-large="images/1.jpg" alt="image01" data-description="From off a hill whose concave womb reworded" /></li>
</ul>
</div>
</div>
<!-- End Elastislide Carousel Thumbnail Viewer -->
</div><!-- rg-thumbs -->
</div><!-- rg-gallery -->
</div><!-- content -->
</div><!-- container -->
Sorry if my English is not so good, but I really need to solve this.
Well I have no idea why would you do that, but if you want to reload the page every time you click on the Next and Prev buttons, including the Thumbnail you could do something like this:
$(document).ready(function() {
$('.es-nav span, .es-carousel img').on('click', function() {
location.reload();
});
});
This will reload the page when you click on the nav or an image in the thumbnail area.

javascript forEach - add addEventListener on all buttons

I'm not so skilled with javascript so I'm looking for a little help.
I'm using a script found on Codrops (3D Grid Effect - http://tympanus.net/Development/3DGridEffect/).
All is working fine as expected but I'm trying to "modify" it for my needs.
Basically, I want to trigger the "effect" NOT clicking on the whole container but on a button placed inside it.
The structure I'm using is:
<section class="grid3d vertical" id="grid3d">
<div class="grid-wrap">
<div class="grid">
<div class="box"><div class="btn-click-me">Click to Show</div></div>
<div class="box"><div class="btn-click-me">Click to Show</div></div>
<div class="box"><div class="btn-click-me">Click to Show</div></div>
</div>
</div>
<div class="content">
<div>
<div class="dummy-img"></div>
<p class="dummy-text">Some text</p>
<p class="dummy-text">Some more text</p>
</div>
<div>
<!-- ... -->
</div>
<!-- ... -->
<span class="loading"></span>
<span class="icon close-content"></span>
</div>
</section>
<script>
new grid3D( document.getElementById( 'grid3d' ) );
</script>
And the script (js) is
/**
* grid3d.js v1.0.0
* http://www.codrops.com
*
* Licensed under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2014, Codrops
* http://www.codrops.com
*/
;( function( window ) {
'use strict';
function grid3D( el, options ) {
this.el = el;
this.options = extend( {}, this.options );
extend( this.options, options );
this._init();
}
// any options you might want to configure
grid3D.prototype.options = {};
grid3D.prototype._init = function() {
// grid wrapper
this.gridWrap = this.el.querySelector( 'div.grid-wrap' );
// grid element
this.grid = this.gridWrap.querySelector( 'div.grid' );
// main grid items
this.gridItems = [].slice.call( this.grid.children );
// default sizes for grid items
this.itemSize = { width : this.gridItems[0].offsetWidth, height : this.gridItems[0].offsetHeight };
// content
this.contentEl = this.el.querySelector( 'div.content' );
// content items
this.contentItems = [].slice.call( this.contentEl.children );
// close content cross
this.close = this.contentEl.querySelector( 'span.close-content' );
// loading indicator
this.loader = this.contentEl.querySelector( 'span.loading' );
// support: support for pointer events, transitions and 3d transforms
this.support = support.pointerevents && support.csstransitions && support.csstransforms3d;
// init events
this._initEvents();
};
grid3D.prototype._initEvents = function() {
var self = this;
// open the content element when clicking on the main grid items
this.gridItems.forEach( function( item, idx ) {
item.addEventListener( 'click', function() {
self._showContent( idx );
} );
} );
// close the content element
this.close.addEventListener( 'click', function() {
self._hideContent();
} );
if( this.support ) {
// window resize
window.addEventListener( 'resize', function() { self._resizeHandler(); } );
// trick to prevent scrolling when animation is running (opening only)
// this prevents that the back of the placeholder does not stay positioned in a wrong way
window.addEventListener( 'scroll', function() {
if ( self.isAnimating ) {
window.scrollTo( self.scrollPosition ? self.scrollPosition.x : 0, self.scrollPosition ? self.scrollPosition.y : 0 );
}
else {
self.scrollPosition = { x : window.pageXOffset || docElem.scrollLeft, y : window.pageYOffset || docElem.scrollTop };
// change the grid perspective origin as we scroll the page
self._scrollHandler();
}
});
}
};
// creates placeholder and animates it to fullscreen
// in the end of the animation the content is shown
// a loading indicator will appear for 1 second to simulate a loading period
grid3D.prototype._showContent = function( pos ) {
if( this.isAnimating ) {
return false;
}
this.isAnimating = true;
var self = this,
loadContent = function() {
// simulating loading...
setTimeout( function() {
// hide loader
classie.removeClass( self.loader, 'show' );
// in the end of the transition set class "show" to respective content item
classie.addClass( self.contentItems[ pos ], 'show' );
}, 1000 );
// show content area
classie.addClass( self.contentEl, 'show' );
// show loader
classie.addClass( self.loader, 'show' );
classie.addClass( document.body, 'noscroll' );
self.isAnimating = false;
};
// if no support just load the content (simple fallback - no animation at all)
if( !this.support ) {
loadContent();
return false;
}
var currentItem = this.gridItems[ pos ],
itemContent = currentItem.innerHTML;
// create the placeholder
this.placeholder = this._createPlaceholder(itemContent );
// set the top and left of the placeholder to the top and left of the clicked grid item (relative to the grid)
this.placeholder.style.left = currentItem.offsetLeft + 'px';
this.placeholder.style.top = currentItem.offsetTop + 'px';
// append placeholder to the grid
this.grid.appendChild( this.placeholder );
// and animate it
var animFn = function() {
// give class "active" to current grid item (hides it)
classie.addClass( currentItem, 'active' );
// add class "view-full" to the grid-wrap
classie.addClass( self.gridWrap, 'view-full' );
// set width/height/left/top of placeholder
self._resizePlaceholder();
var onEndTransitionFn = function( ev ) {
if( ev.propertyName.indexOf( 'transform' ) === -1 ) return false;
this.removeEventListener( transEndEventName, onEndTransitionFn );
loadContent();
};
self.placeholder.addEventListener( transEndEventName, onEndTransitionFn );
};
setTimeout( animFn, 25 );
};
grid3D.prototype._hideContent = function() {
var self = this,
contentItem = this.el.querySelector( 'div.content > .show' ),
currentItem = this.gridItems[ this.contentItems.indexOf( contentItem ) ];
classie.removeClass( contentItem, 'show' );
classie.removeClass( this.contentEl, 'show' );
// without the timeout there seems to be some problem in firefox
setTimeout( function() { classie.removeClass( document.body, 'noscroll' ); }, 25 );
// that's it for no support..
if( !this.support ) return false;
classie.removeClass( this.gridWrap, 'view-full' );
// reset placeholder style values
this.placeholder.style.left = currentItem.offsetLeft + 'px';
this.placeholder.style.top = currentItem.offsetTop + 'px';
this.placeholder.style.width = this.itemSize.width + 'px';
this.placeholder.style.height = this.itemSize.height + 'px';
var onEndPlaceholderTransFn = function( ev ) {
this.removeEventListener( transEndEventName, onEndPlaceholderTransFn );
// remove placeholder from grid
self.placeholder.parentNode.removeChild( self.placeholder );
// show grid item again
classie.removeClass( currentItem, 'active' );
};
this.placeholder.addEventListener( transEndEventName, onEndPlaceholderTransFn );
}
// function to create the placeholder
/*
<div class="placeholder">
<div class="front">[content]</div>
<div class="back"></div>
</div>
*/
grid3D.prototype._createPlaceholder = function( content ) {
var front = document.createElement( 'div' );
front.className = 'front';
front.innerHTML = content;
var back = document.createElement( 'div' );
back.className = 'back';
back.innerHTML = ' ';
var placeholder = document.createElement( 'div' );
placeholder.className = 'placeholder';
placeholder.appendChild( front );
placeholder.appendChild( back );
return placeholder;
};
grid3D.prototype._scrollHandler = function() {
var self = this;
if( !this.didScroll ) {
this.didScroll = true;
setTimeout( function() { self._scrollPage(); }, 60 );
}
};
// changes the grid perspective origin as we scroll the page
grid3D.prototype._scrollPage = function() {
var perspY = scrollY() + getViewportH() / 2;
this.gridWrap.style.WebkitPerspectiveOrigin = '50% ' + perspY + 'px';
this.gridWrap.style.MozPerspectiveOrigin = '50% ' + perspY + 'px';
this.gridWrap.style.perspectiveOrigin = '50% ' + perspY + 'px';
this.didScroll = false;
};
grid3D.prototype._resizeHandler = function() {
var self = this;
function delayed() {
self._resizePlaceholder();
self._scrollPage();
self._resizeTimeout = null;
}
if ( this._resizeTimeout ) {
clearTimeout( this._resizeTimeout );
}
this._resizeTimeout = setTimeout( delayed, 50 );
}
grid3D.prototype._resizePlaceholder = function() {
// need to recalculate all these values as the size of the window changes
this.itemSize = { width : this.gridItems[0].offsetWidth, height : this.gridItems[0].offsetHeight };
if( this.placeholder ) {
// set the placeholders top to "0 - grid offsetTop" and left to "0 - grid offsetLeft"
this.placeholder.style.left = Number( -1 * ( this.grid.offsetLeft - scrollX() ) ) + 'px';
this.placeholder.style.top = Number( -1 * ( this.grid.offsetTop - scrollY() ) ) + 'px';
// set the placeholders width to windows width and height to windows height
this.placeholder.style.width = getViewportW() + 'px';
this.placeholder.style.height = getViewportH() + 'px';
}
}
// add to global namespace
window.grid3D = grid3D;
})( window );
Now, I'm aware that the "crucial" portion of the code where I have to look is:
// open the content element when clicking on the main grid items
this.gridItems.forEach( function(item, idx ) {
item.addEventListener( 'click', function() {
item._showContent( idx ); } ); } );
So, my question again: how to trigger the event when the div (button) class "click-me" is clicked on every "boxes"?
Thanks to all in advance (i'm struggling with it for hours...)
Have a look at the example here,
http://jsfiddle.net/y0mbn94n/
I have added some intialisation to get your particular classes
// get grid buttons and then make an iterable array out of them
this.gridButtons = this.el.querySelectorAll('button.btn-click-me');
this.gridButtonItems = [].slice.call(this.gridButtons);
and changed the function which iterates and adds a listener.
// open the content element when clicking on the buttonsItems
this.gridButtonItems.forEach(function (item, idx) {
item.addEventListener('click', function () {
self._showContent(idx);
});
});
If you want to call a callback function when the user clicks on a button:
var buttons = document.querySelectorAll('.btn-click-me');
for (var i = 0; i < buttons.length; i++) {
var self = buttons[i];
self.addEventListener('click', function (event) {
// prevent browser's default action
event.preventDefault();
// call your awesome function here
MyAwesomeFunction(this); // 'this' refers to the current button on for loop
}, false);
}
with the structure given
<div class="grid-wrap">
<div class="grid">
<div class="box"><div class="btn-click-me">Click to Show</div></div>
<div class="box"><div class="btn-click-me">Click to Show</div></div>
<div class="box"><div class="btn-click-me">Click to Show</div></div>
</div>
</div>
you just have to change the line you've said to:
item.children[0].addEventListener( 'click', function() {
as the btn-click-me would be the first child of each item.
If you would like a more generic solution you could use:
item.getElementsByClassName('btn-click-me')[0].addEventListener( 'click', function() {
where bnt-click-me would be the class of the button that you would want to bind the click event. Notice that [0] so you can select the very first item of the array, as getElementsByClassName will return one, even if there's only one element.
But if you say you're just starting with javascript y really recommend you using jQuery, it's selectors are much easier than vanilla javascript.

Hash is not Full in the URL

I have a gallery in Jquery Elastislide.
var imageIndex = 0;
if (window.location.hash) {
var imageIndexStr = window.location.hash.replace('#',''); // remove #
imageIndex = parseInt(imageIndexStr, 0); // convert to int
}
Thanks to the code above, The gallery got pictures with corresponding Hash.
www.example.com/gallery.html#1_TITLE_OF_THE_PICTURE
When I put the code to navigate with arrows of the gallery, I get in the following URL :
www.example.com/gallery.html#1
_navigate = function( dir ) {
// navigate through the large images
if( anim ) return false;
anim = true;
if( dir === 'right' ) {
if( current + 1 >= itemsCount )
current = 0;
else
++current;
}
else if( dir === 'left' ) {
if( current - 1 < 0 )
current = itemsCount - 1;
else
--current;
}
_showImage( $items.eq( window.location.hash = current) );
So, I want some help in order to get in the URL the full Hash.
www.example.com/gallery.html#1_TITLE_OF_THE_PICTURE
HTML Code :
<head>
<style>
.es-carousel ul{
display:block;
}
</style>
<script id="img-wrapper-tmpl" type="text/x-jquery-tmpl">
<div class="rg-image-wrapper">
{{if itemsCount > 1}}
<div class="rg-image-nav">
Previous Image
Next Image
</div>
{{/if}}
<div class="rg-image"></div>
<div class="rg-loading"></div>
<div class="rg-caption-wrapper">
<div class="rg-caption" style="display:none;">
<p></p>
</div>
</div>
</div>
</script>
</head>
<body>
<div class="container_gallery">
<div id="rg-gallery" class="rg-gallery">
<div class="rg-thumbs">
<!-- Elastislide Carousel Thumbnail Viewer -->
<div class="es-carousel-wrapper">
<div class="es-nav">
<span class="es-nav-prev">Previous</span>
<span class="es-nav-next">Next</span>
</div>
<div class="es-carousel">
<ul>
<li> <img src="picture_thumb.jpg" data-large="picture.jpg" alt="Title_1" data-description="Title_1" /></li>
href="#0_Title_2"><img src="picture2_thumb.jpg" data-large="picture2.jpg" alt="Title_2" data-description="Title_2" /></a></li>
href="#0_Title_3"><img src="picture3_thumb.jpg" data-large="picture3.jpg" alt="Title_3" data-description="Title_3" /></a></li>
</ul>
</div>
</div>
<!-- End Elastislide Carousel Thumbnail Viewer -->
</div><!-- rg-thumbs -->
</div><!-- rg-gallery -->
</div>
Event Navigation :
$('#img-wrapper-tmpl').tmpl( {itemsCount : itemsCount} ).prependTo( $rgGallery );
if( itemsCount > 1) {
// addNavigation
var $navPrev = $rgGallery.find('a.rg-image-nav-prev'),
$navNext = $rgGallery.find('a.rg-image-nav-next'),
$imgWrapper = $rgGallery.find('div.rg-image');
$navPrev.on('click.rgGallery', function( event ) {
_navigate( 'left' );
return false;
});
$navNext.on('click.rgGallery', function( event ) {
_navigate( 'right' );
return false;
});
// add touchwipe events on the large image wrapper
$imgWrapper.touchwipe({
wipeLeft : function() {
_navigate( 'right' );
},
wipeRight : function() {
_navigate( 'left' );
},
preventDefaultEvents: false
});
$(document).on('keyup.rgGallery', function( event ) {
if (event.keyCode == 39)
_navigate( 'right' );
else if (event.keyCode == 37)
_navigate( 'left' );
});
}
},
Thanks for your answers.
This line of code is setting the hash value to just be a number which would cause it to become something like: www.example.com/gallery.html#1.
_showImage( $items.eq( window.location.hash = current) );
It looks to me like your navigate function is not putting the title onto the new hash value when you change pictures. I think you want something like this:
window.location.hash = current + "_" + newPictureTitle;
_showImage( $items.eq(current) );
Where you obviously need to fill in the value of newPictureTitle
Based on the HTML and other javascript you've shown, your _navigate() function could work like this:
_navigate = function( dir ) {
// navigate through the large images
if( anim ) return false;
anim = true;
if( dir === 'right' ) {
if( ++current >= itemsCount )
current = 0;
} else if( dir === 'left' ) {
if( --current < 0 )
current = itemsCount - 1;
}
// show the right image
_showImage( $items.eq(current) );
// now get the right image title so it can go in the hash value
// we assume here that current is a zero based index
var links = $("#rg-gallery .es-carousel li a");
// use getAttribute here to get the raw href that's in the
// HTML source file (not a fully qualified URL)
window.location.hash = links.get(current).getAttribute("href");
}

How to get the url from link rel="next" in <head> with javascript

How to get the url from
<link rel="prev" title="Selected 3" href="http://mydomain.com/2.html" />
in the head using pure javascript?
In jquery I have a working solution:
var prevUrl = $('link[rel=prev]').attr("href");
I can't change the output of the "link rel" or add an Id, as it is generated by a CMS.
Any help is greatly appreciated, thanks.
IE8+
document.querySelector('link[rel="prev"]').href;
var links = document.getElementsByTagName( "link" ),
filtered = [],
i = links.length;
while ( i-- ) {
links[i].rel === "prev" && filtered.push( links[i] );
}
alert( filtered[0].href );
Demo: http://jsfiddle.net/je7Qr/
var links = document.getElementsByTagName("link");
for (var i = 0; typeof(el = links[i]) != "undefined"; i++) {
if (el.rel == "prev") {
alert(el.href);
break;
}
}

Using Javascript to move a div wont work

I have some javascript that should move my div element every 400 milliseconds. From debugging I have found that all my code works except when I go to move the div element. Ie, this code:
block.style.left = xPos[index] + "px";
I am unsure why this code doesn't move my div? Should I use a different method (other than object.style.top etc.) to move my div?
My java script:
<script LANGUAGE="JavaScript" type = "text/javascript">
<!--
var block = null;
var clockStep = null;
var index = 0;
var maxIndex = 6;
var x = 0;
var y = 0;
var timerInterval = 400; // milliseconds
var xPos = null;
var yPos = null;
function moveBlock()
{
//alert( index ); // if you use this you will see my setInterval works fine
if ( index < 0 || index >= maxIndex || block === null || clockStep === null )
{
clearInterval( clockStep );
clockStep = null;
return;
}
block.innerHTML = "yellow"; // this works (just a debug test) so I know block points to the correct HTML element
block.style.left = xPos[index] + "px"; // this doesn't work
block.style.top = yPos[index] + "px";
index++;
}
function onBlockClick( blockID )
{
if ( clockStep !== null )
{
return;
}
block = document.getElementById( blockID );
index = 0;
x = parseInt( block.style.left, 10 );
y = parseInt( block.style.top, 10 );
xPos = new Array( x+10, x+20, x+30, x+40, x+50, x+60 );
yPos = new Array( y-10, y-20, y-30, y-40, y-50, y-60 );
clockStep = setInterval( "moveBlock()", timerInterval );
}
-->
</script>
The value of block.style.left and block.style.top is not set unless you use an absolutely-positioned div with preset values for both left and top (in fact, your array is filled with NaN when I tested). For instance, the code works fine with a div defined like this:
<div id="div1" style="position:absolute;left:100px;top:100px;
width:150px;height:150px;background-color:yellow;"
onclick="onBlockClick(this.id);">
HI
</div>

Categories