0

I have several DIVs on my page that belong to the same class and contain short statements with links automatically generated by FlowDock (adding links to @mentions).

Is there a way NOT to redirect a user to another URL, but instead to call on a function when they click on that link, which would filter the statements on that page, showing only the .entry DIVs that contain the @mention that was clicked on?

Here's an example:

<div class='entry' data-hashtags='#supermarkets #food #alcohol'>
    <p>#supermarkets sell #food and #alcohol <a title="Search @private" class="app-tag-link" href="/context/@private">@private</a></p>
</div>

The user clicks on @private and instead of going to /context/@private a JavaScript function is called that filters the DIVs through jQuery, as is shown here.

Thank you for your help!

Community
  • 1
  • 1
Aerodynamika
  • 6,253
  • 10
  • 54
  • 104

1 Answers1

2

Sure - you want to attach a listener to the link and call preventDefault to prevent the default behavior of the link (which is to redirect).

Without using jQuery:

element.addEventListener('click', function(e) {
  e.preventDefault();
  // Filter
});

Fiddle

Using jQuery:

// jQueryObject holds the selected set of element(s)
jQueryObject.on('click', function(e) {
  e.preventDefault();
  // Filter
});
linstantnoodles
  • 3,997
  • 1
  • 16
  • 23
  • Thanks, @linstantnoodles! This works, for the first element. But if I want to have this same behavior for all the elements of the class on the page? I tried removing [0] from jsfiddle and it doesn't work. Could also reiterate the array I guess, but maybe an easier solution? Sorry, I'm a beginner :) – Aerodynamika Feb 17 '14 at 22:28
  • In the end I did with the For loop: http://jsfiddle.net/jd7z3/2/ - is this an efficient way to do something like that? – Aerodynamika Feb 17 '14 at 22:29
  • 1
    You can either take advantage of event delegation ([here](http://davidwalsh.name/event-delegate) or [here](http://stackoverflow.com/questions/1687296/what-is-dom-event-delegation) or jQuery ([fiddle](http://jsfiddle.net/jd7z3/4/)). Otherwise, I think you have to use the for-loop because the DOM api doesn't offer a way to attach listeners to lists of elements. – linstantnoodles Feb 17 '14 at 23:36