I have been attempting to create a dynamic jQuery image gallery that does not require the user to be taken to a new destination when they click a link. It can be found here – http://the-session.co.uk/JSgallery/
I have created the showPic function which takes 2 arguments – the event object and an element node object (a specific element that is clicked on with a class of link) . The source variable uses the .attr() method and acts as a “getter” to get the src attribute of the element node passed to the showPic function.
I have then stored the <img id="placeholder"> in a variable called gallery. The idea was then to set the src attribute of gallery to the src from the source variable.
I have then used event.preventDefault(); so that the the default action of the event will not be triggered. However the elements are still taking the user to a new destination which is not desired.
The final step was to select .link (the <a> elements) and then use the .on method so that when a user clicks an anonymous function is invoked. The showPic function is then called and it is passed the specific element that was clicked on using $(this).
Currently the code is not working and I do not understand why. Any suggestions?
function showPic (event, el) {
var source = el.attr('source'); // getter
var gallery = $('#placeholder'); // <img id="placeholder">
gallery.attr('src', source); // setter
event.preventDefault();
}
$('.link').on('click', function() {
showPic($(this));
});
You’ll need to pass the event as well, when inside a function like that :
On the other hand if you reference the function directly the event will be passed, and you can use event.target to get the clicked element, if that is the same as the bound element: