0

I have a slideshow on my site - it all works as it should - But I want to change the navigation for it to be unobtrusive.

How do I do it? The navigation is:

<a href="javascript:slideshow.previous()" id="slideshow_prev" ><span>&lt;prev</span></a>
<a href="javascript:slideshow.slideshow.play()" id="slideshow_start" ><span>start</span></a>
<a href="javascript:slideshow.hotlink()" id="slideshow_view" ><span>view</span></a>
<a href="javascript:slideshow.pause()" id="slideshow_stop" ><span>stop</span></a>
<a href="javascript:slideshow.next()" id="slideshow_next" ><span>next&gt;</span></a>
Conrad M
  • 203
  • 1
  • 3
  • 11
  • 1
    Using [closures/scopes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures) and [self executing anonymous functions](http://stackoverflow.com/q/592396/1960455), and [`addEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener) and make sure it is useable without javascript. – t.niese Jan 11 '14 at 18:12

2 Answers2

0

You can attach events after they are loaded into the dom. There are differances in how IE and wc3 attach events are handled, this is where libraries like jquery shine because they normalize the event model.

adding event listener cross browser http://www.quirksmode.org/js/events_advanced.html

jquery

$('#slideshow_prev').click(slideshow.previous);

without jquery w3c standard

document.getElementById("slideshow_prev").addEventListener("click", slideshow.previous);

for legacy ie

document.getElementById("slideshow_prev").attachEvent('onclick',slideshow.previous)
Community
  • 1
  • 1
JustEngland
  • 1,371
  • 13
  • 30
0

Here's a basic example.

First, remove any inline javascript:

<a id="slideshow_prev" ><span>&lt;prev</span></a>
<a id="slideshow_start" ><span>start</span></a>
<a id="slideshow_view" ><span>view</span></a>
<a id="slideshow_stop" ><span>stop</span></a>
<a id="slideshow_next" ><span>next&gt;</span></a>

Get element references:

var prev = document.getElementById('slideshow_prev');
var start = document.getElementById('slideshow_start');
//etc

Attach event listeners to each element:

prev.addEventListener('click', slideshow.previous);
start.addEventListener('click', slideshow.slideshow.play);
//etc

Optimize/Automate

Rather than manually getting each reference and attaching the listeners, I created an object to associate an id with a function, then iterated over the object's properties to automate the process: Live demo (click).

var x = { 
  slideshow_prev: slideshow.previous,
  slideshow_start: slideshow.slideshow.play,
  slideshow_view: slideshow.hotlink,
  slideshow_stop: slideshow.pause,
  slideshow_next: slideshow.next
};

for (var prop in x) {
  var elem = document.getElementById(prop);
  var clickFunc = x[prop];
  elem.addEventListener('click', clickFunc);
}
m59
  • 43,214
  • 14
  • 119
  • 136