I realize that this posting is possibly a repeat of this one:
Using Javascript to dynamically create links that trigger popup windows
But I'm not good enough at JavaScript to understand how to apply it to the context in which I'm trying to do it.
I'm creating a javascript snippet that could possibly be called multiple times from within a CMS (Umbraco ) that generates webpages.
An id (variable name: mediaid) is passed into this context and I want to dynamically create a link that has an onclick event to launch a popup. I take the ID passed into the context I'm working in (Umbraco calls them "macros") and append the id as a query string to a different URL (same domain) so that the resultant page can do some stuff with the id.
What I have works, but only for one instance on a page. I need a user to be able to insert multiple dynamic links on a page. Right now, the last link generated uses the onclick event for all instances on the page.
<script>
var linkWithQueryParam = 'http://www.mydomain.org/test2?yourkey=<xsl:value-of select="$mediaid" />';
var element = document.createElement("a");
element.id = '<xsl:value-of select="$mediaid" />';
element.href = '#';
element.onclick = function() {
setLink(linkWithQueryParam);
}
function setLink(value) {
window.open(value, 'player', 'width=775,height=520,location=0,directories=0,status=0,menubar=0');
}
document.body.appendChild(element);
element.appendChild(document.createTextNode('Listen To This Audio'));
</script>
So, for example, I have a template elsewhere, that calls this macro I created, twice:
<umbraco:Macro mediaid="4107" Alias="audioPlayerPopUp" runat="server"></umbraco:Macro>
<umbraco:Macro mediaid="26502" Alias="audioPlayerPopUp" runat="server"></umbraco:Macro>
The links are generated, but when I click on them, the link generated above in "linkWithQueryParam" is always whatever the last one was, for all links.
I thought maybe if I set the "id" attribute of the link to make it unique, it would work. But that doesn't work. How can I make the dynamically generated onclick event unique?
I ended up changing my approach and using an event delegate per unclenorton's response in this s.o. post
http://davidwalsh.name/event-delegate
I used a variation on the example to only disable the default link behavior, first checking to see that the link class is matched. This script relies on a named div that is available sitewide and is placed at the bottom of a master template so it is available:
<script>
document.getElementById("main").addEventListener("click", function(e) {
if(e.target)
{
if(e.target.nodeName == "A")
{
if(e.target.className == "miniplayer")
{
if(e.preventDefault) {
e.preventDefault();
}
else
{
e.returnValue = false;
}
var target = e.target;
var popupWindows = window.open(target.href, 'player', 'width=775,height=520,location=0,directories=0,status=0,menubar=0');
}
}
}
});
</script>
I then edited my user macro to simply place the class "miniplayer" on each link it creates and include the media id as a query parameter to another url which provides the media player. That other url resource then pulls the query param id out of the url and looks up the link to the media item. But the .js above launches the pop-up the way that I want.
One challenge I had was on how to dynamically assign the resultant media resource to the player (in this case, jPlayer). I found that if I write the media url to a hidden div, I can then just tell the jPlayer to read the value from it.
So I have a second macro which gets the query param and writes it to a hidden div:
<div style="display:none" id="audioUrl"><xsl:copy-of select="$mediaNode/audioUrl" /></div>
Finally, I adjust the jPlayer jQuery to read the url from the hidden div:
$(this).jPlayer('setMedia', {mp3: $("#audioUrl").text() }).jPlayer("play");
It doesn't seem like the best solution. I don't like passing the mediaid through the url, but it fulfills all my other requirements
The issue here is with globals and closures. The linkWithQueryParam variable is a global that is updated each time that script is added. When you click on the link it goes and fetches the url from the variable which is of course the last one.
You can fix this a few ways,
Wrap this code in an immediate anonymous function. This will reduce the scope of the variables to within the anonymous function.
Set the URL when the script is run instead of when the link is clicked.
Related
I have an index view of cards (e.g. playing cards) laid out in a BootStrap grid. Each card is in a div, and I have a jQuery click handler for each div, to open a details page for any card (card div) that is clicked. So the redirect from the index to detail view is all accomplished using this (rather smelly) JavaScript:
var showDetail = function (index) {
const newUrl = "#($"http://{Model.HostName}{Url.Action("Details", "Card")}/")" + index;
window.location = newUrl;
};
I don't like to depend on the Razor code nugget to give me the hostname and the url's path. Does JavaScript have any functionality that I can use to achieve the same as the above dodgy code?
You can create create an anchor on the fly and read its href property.
console.log($('<a>', {
"href": '/test/for/relative/url'
}).prop('href'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
And, Also URL API can be used.
i am trying to show a div which is currently hide and inside body tag.by changing url using anchor tag attribute href.Like below---
<a id="ai" href="managevendors" class="tablink" onclick="openCity()">Manage Vendors
</a>
<div class="w3-container city" style="display: none;" id="managevendors">
<h1>hi,how are you</h1>
</div>
when i click on this anchor tag my url will definitely changed.and based on url i wants to display a div.
my js code...
function openCity() {
if (window.location.hash == "managevendors") {
$("#managevendors").show();
}
}
i dont know why this is not working.but i teide with different way like below..
<a id="ai" href="#managevendors" class="tablink" onclick="openCity('managevendors')">Manage Vendors
</a>
and js code.....
function openCity()
{
if (window.location.hash == "#managevendors") {
$("#managevendors").show();
}
}
but i dont want the # sing,how can i solve it.help me experience brothers.thanks in advance.
You must use the hash if you expect the navigation to work. Once you do that, you don't need to check for it, you can just show the section:
$("#ai").on("click", openCity);
function openCity() {
// The only reason this code is running is because the link was clicked.
// No need to test for it.
$("#managevendors").show();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- You have to include the hash in the href for navigation to work -->
<a id="ai" href="#managevendors" class="tablink">Manage Vendors
</a>
<div class="w3-container city" style="display: none;" id="managevendors">
<h1>hi,how are you</h1>
</div>
I think the problem here is that you are using an anchor tag when you should be using a button. The reason the first way is not working is due to the page refreshing when you click the link.
Try changing your <a> to a <button>
From what I understand, you most likely need the href="#xyz" with a hash. This will keep clientside logic active without trying to solve the url and take a detour to the server for nothing. If you're going to capture that part, keep it local.
I suggest to remove the onclick handler from HTML. To capture the link you can use jQuery to keep your HTML "clean". If you must, for some odd reason, by all means you can reference onclick="openCity(this)", so the element you click on is passed directly to openCity.
// vanilla
function openCity(element){
var href = element.getAttribute('href'), // expecting a hash here
id = href.substr(1), // remove the hash
target = document.getElementById(id);
target.className += " active";
return false;
}
As Scott suggests with jQuery:
//$('.tablink').on('click', openCity);
$('.tablink[href^="#"]').on('click', openCity);
Then the function can be made dynamic by referencing the href from the clicked element:
function openCity(ev){
var el = $(ev.currentTarget),
id = el.prop('href'), // expecting a hash here
target = $(id);
// since you're providing both with and without hash, the default behaviour is to follow the link, unless referenced with a hash
ev.preventDefault();
target.addClass('active');
}
If the id was not found on the page, this will void silently.
Now if you want to work with the url as entry point, note that this will only happen on load event => share a link and someone clicks on it (with the #xyz attached) or type directly in the address bar.
// 1. bind the event
$(window).load(function(){
/*loadCity defined here or outside*/
loadCity();
});
// 2. define what happens
function loadCity(){
var id = window.location.hash, // expecting a hash here
target = $(id);
target.addClass('active');
}
Since this solution only solves state of an element, the actual show/hide part can be made in CSS. Very simple as you probably already did or with animations, transitions and so on.
.city { display: none; }
.city.active { display: block; }
I have a shadowbox script. When I load the page everything works fine, but when I call this jquery load function and then try to trigger the shadowbox by clicking on the image, the large image opens in new window instead.
Here's the code:
<link href="CSS/main.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="shadowbox-3.0.3/shadowbox.js"></script>
<script type="text/javascript">
Shadowbox.init();
</script>
<p id="compas"></p>
Any idea why this is happening?
EDIT
So, we finally get the bottom of this. 15 hours after first commenting on this issue, and at least 50 iterations later, we finally have identified what the problem is and how to fix it.
It actually struck me suddenly when I was creating local aaa.html and bbb.html on my server. That was when it hit me that the element nodes for the content that was being replaced was being removed altogether from the DOM when $.load() runs the callback function. So, once the #menu-home content elements were replaced, they were removed from the DOM and no longer had Shadowbox applied to them.
Once I figured this out, it was just a matter of a single web search and I found:
Nabble-Shadowbox - Reinit Shadowbox
Specifically, the response from mjijackson. What he describes is how to "restart" (reinitialize) Shadowbox using:
Shadowbox.clearCache();
Shadowbox.setup();
So once the #menu-home content was reloaded, what needs to happen is the Shadowbox cache needs to be cleared (essentially, shutting it down on the page), then the Shadowbox.setup() is run, which will detect the elements all over again. You don't run the Shadowbox.init() method again either.
I noticed that you had tried to copy/paste the Shadowbox.setup() in after the $.load(), at least sequentially in the code. However, this wasn't going to work, due to the cache clearing that needs to happen first, and primarily because the .clearCache() and .setup() functions need to be run after the $.load() completes (finishes and runs any callbacks). Those two functions need to be run in the $.load() callback handler; otherwise, you're running it's immediately, but the $.load() is asynchronous and will complete at some later time.
I'm going to go over some other changes I made, just so you understand what, why and wherefore.
Note, I'm not sure if you're familiar with <base>, but the following is at the top of the HEAD element:
<base href="http://62.162.170.125/"/>
This just let's me use the resource files on your computer. You'll not want to use this on your actual site more than likely. If you copy/paste, make sure and remove this line.
<div id="menu">
<ul>
<li><a id="menu-home" href="index.html" rel="http://jfcoder.com/test/homecontent.html">Home</a></li>
<li><a id="menu-services" href="services.html" rel="http://jfcoder.com/test/servicescontent.html">Services</a></li>
<li><a id="menu-tour" href="tour.html" rel="http://jfcoder.com/test/tourcontent.html">Tour</a></li>
<li><a id="menulogin" href="login.html">Login</a></li>
</ul>
</div>
Here, you'll notice I have a relative url in the HREF attribute, and a link to some pages on my server. The reason for the links to my server is that I couldn't access your aaa.html and bbb.html files through AJAX due to cross-site scripting limitations. The links to my website should be removed as well.
Now, the reason I'm using the rel attribute here is that I want allow for the links by way of the href attribute to continue to work in case the JS doesn't function correctly or there's some other error. If you have separate files, one for full HTML document and another for just the fragments, this is what you'll want to do. If you can serve both the full document AND the content-only from the linked file, then you probably don't need the rel attribute, but you'll need to manage the request so the server knows how to respond (full document or just the content part).
var boxInitialize = function(){
try {
if (!Shadowbox.initialized) {
Shadowbox.init();
Shadowbox.initialized = true;
} else {
Shadowbox.clearCache();
Shadowbox.setup();
}
} catch(e) {
try {
Shadowbox.init();
} catch(e) {};
}
};
All I've done here is create a central location for the initialization/setup requests. Fairly straightforward. Note, I added the Shadowbox.initialized property so I could keep track of if the Shadowbox.init() had run, which can only be run once. However, keeping it all in one spot is a good idea if possible.
I also created a variable function which can be called either as a regular function:
boxInitialize();
Or as a function reference:
window.onload = boxInitialize; // Note, no () at the end, which execute the function
You'll probably notice I removed the $() and replaced them with jQuery() instead. This can turn into a real nightmare if you end up with an environment with multiple frameworks and libraries competing for $(), so it's best to avoid it. This actually just bit me real good the other day.
Since we have a closure scope within the .ready() callback, we can take advantage of that to save several "private" variables for ow use at different times in the scripts execution.
var $ = jQuery,
$content = jQuery("#content"), // This is "caching" the jQuery selected result
view = '',
detectcachedview = '',
$fragment,
s = Object.prototype.toString,
init;
Note the , at the end of all but the last line. See how I "imported" the $ by making it equal to the jQuery variable, which means you could actually use it in that#.
var loadCallback = function(response, status, xhr){
if (init != '' && s.call(init) == '[object Function]') {
boxInitialize();
}
if (xhr.success()
&& view != ''
&& typeof view == 'string'
&& view.length > 1) {
$fragment = $content.clone(true, true);
cacheContent(view, $fragment);
}
};
This runs when the $.load() completes the process of the AJAX request. Note, the content returned in the request has already been placed on the DOM by the time this runs. Note as well that we're storing the actual cached content in the $content.data(), which should never be removed from the page; only the content underneath it.
var cacheContent = function(key, $data){
if (typeof key == 'string'
&& key.length > 1
&& $data instanceof jQuery) {
$content.data(key, $data.html());
$content.data(detectcachedview, true);
}
};
cacheContent() is one a method you may not want; essentially, if it was already loaded on a previous request, then it will be cached and then directly retrieved instead of initiating another $.load() to get the content from the server. You may not want to do this; if so, just comment out the second if block in the menuLoadContent() function.
var setContent = function(html){
$content.empty().html(html);
if (init != '' && s.call(init) == '[object Function]') {
boxInitialize();
}
};
What this does is first empty the $content element of it's contents/elements, then add the specified string-based markup that we saved earlier by getting the $content.html(). This is what we'll re-add when possible; you can see once the different links have been clicked and loaded, reclicking to get that to redisplay is really quick. Also, if it's the same request as currently loaded, it also will skip running the code altogether.
(We use $content like because it is a reference to a variable containing a jQuery element. I am doing this because it's in a closure-scope, which means it doesn't show up in the global scope, but will be available for things like event handlers.
Look for the inline comments in the code.
var menuLoadContent = function(){
// This is where I cancel the request; we're going to show the same thing
// again, so why not just cancel?
if (view == this.id || !this.rel) {
return false;
}
// I use this in setContent() and loadCallback() functions to detect if
// the Shadowbox needs to be cleared and re-setup. This and code below
// resolve the issue you were having with the compass functionality.
init = this.id == 'menu-home' ? boxInitialize : '';
view = this.id;
detectcachedview = "__" + view;
// This is what blocks the superfluous $.load() calls for content that's
// already been cached.
if ($content.data(detectcachedview) === true) {
setContent($content.data(view));
return false;
}
// Now I have this in two different spots; there's also one up in
// loadCallback(). Why? Because I want to cache the content that
// loaded on the initial page view, so if you try to go back to
// it, you'll just pickup what was sent with the full document.
// Also note I'm cloning $content, and then get it's .html()
// in cacheContent().
$fragment = $content.clone(true, true);
cacheContent(view, $fragment);
// See how I use the loadCallback as a function reference, and omit
// the () so it's not called immediately?
$content.load(this.rel, loadCallback);
// These return false's in this function block the link from navigating
// to it's href URL.
return false;
};
Now, I select the relevant menu items differently. You don't need a separate $.click() declaration for each element; instead, I select the #menu a[rel], which will get each a element in the menu that has a rel="not empty rel attribute". Again, note how I use menuLoadContent here as a function reference.
jQuery("#menu a[rel]").click(menuLoadContent);
Then, at the very bottom, I run the boxInitialize(); to setup Shadowbox.
Let me know if you have any questions.
I think I might be getting to the bottom of this. I think the flaw is the way you're handling the $.load() of the new content when clicking a menu item, coupled with an uncaught exception I saw having to do with an iframe:
Uncaught exception: Unknown player iframe
This Nabble-Shadowbox forum thread deals with this error. I'm actually not getting that anymore, however I think it came up with I clicked on the tour menu item.
Now, what you're doing to load the content for the menu items really doesn't make any sense. You're requesting an entire HTML document, and then selecting just an element with a class="content". The only benefit I can see for doing this is that the page never reloads, but you need to take another approach to how to get and display the data that doesn't involve downloading the entire page through AJAX and then trying to get jQuery to parse out just the part you want.
I believe handling the content loading this way is the root cause of your problem, hence the $.load() toggling of menu views breaks your page in unexpected ways.
Question: Why don't you just link to the actual page and skip all the $.load() fanciness? Speed-wise, it won't make that much of an impact, if any at all. It just doesn't make sense to use AJAX like this, when you could just link them to the same content without issue.
There are two alternatives that would allow you to prevent roundtrip page reloads:
Setup your AJAX calls to only request the .content portion of the markup if you have the ?contentonly=true flag in the URL, not the entire HTML document. This is how it's traditionally done, and is usually relative simple to do if you have a scripting environment.
$(".content").load('index.html?contentonly=true');
Then your server responds only with the content view requested.
Serve all of the content views within the same HTML document, then show as appropriate:
var $content = $('.content');
$content.find('.content-view').hide();
$content.find('#services-content').show();
It doesn't look like you have a whole lot of content to provide, so the initial page load probably won't have that much of an impact with this particular approach. You might have to look into how to preload images, but that's a very well known technique with many quality scripts and tutorials out there.
Either one of these techniques could use the #! (hashbang) technique to load content, although I believe there are some issues with this for search engines. However, here is a link to a simple technique I put together some time ago:
http://jfcoder.com/test/hash.html
Also, this is just a tip, but don't refer to your "content" element with a class, ie, .content. There should only be one content-displaying element in the markup, right? There's not more than one? Use an id="content"; that's what ID attributes are for, to reference a single element. classes are meant to group elements by some characteristic they share, so above when I .hide() the inline content views (see #2), I look for all of the class="content-view" elements, which are all similar (they contain content view markup). But the $content variable should refer to $('#content');. This is descriptive of what the elements are.
This worked for us, we made a site that used vertical tabs and called in the pages with our shadowbox images using jQuery.load
Just give all of your anchor tags the class="sbox" and paste this script in the header.
<script>
Shadowbox.init({
skipSetup:true,
});
$(document).ready(function() {
Shadowbox.setup($('.sbox'));//set up links with class of sbox
$('a.sbox').live('click',function(e){
Shadowbox.open(this);
//Stops loading link
e.preventDefault();
});
});
</script>
Note: we had to put the .sbox class on all our rel="shadowbox" anchors as well as the on the anchor for the tab that called the .load
Thanks to this guy-> http://www.webmuse.co.uk/blog/shadowbox-ajax-and-other-generated-content-with-jquery-and-javascript/
Well, based on Shem's answer, this is my solution.
Every click on specific class, setup and open shadowbox with elements from same class:
jQuery('.sb-gallery a').live('click',function(e){
Shadowbox.setup(jQuery('.sb-gallery a'));
Shadowbox.open(this);
//Stops loading link
e.preventDefault();
});
Thanks to all
I would like to refire the styling and processing.js scripts that i linked to in the head so that they display correctly when brought in through an ajax-request. I see where in the ajax request this code needs to be, but i don't know how to tell the code to simply reapply the script. I've seen people using getScript() to do this, but from what i can tell this reloads the script, rather than simply telling it repeat or refire. Do all of the scripts need their own reinitialization? I found the syntax highlighters .highlight() method, but i am yet to get the processing script to load. currently, Processing.loadSketchFromSources($('#processing'), ['mysketch.pde']); does not work. I am using current versions of all libraries. Surprised i haven't been able to find the answer yet, as a lot of people seem to have the same problem. Thanks for your help!
index page:
$(document).ready(function () {
// put all your jQuery here.
//Check if url hash value exists (for bookmark)
$.history.init(pageload);
//highlight the selected link
$('a[href=' + document.location.hash + ']').addClass('selected');
//Search for link with REL set to ajax
$('a[rel=ajax]').live("click",function(){
//grab the full url
var hash = this.href;
//remove the # value
hash = hash.replace(/^.*#/, '');
//for back button
$.history.load(hash);
//clear the selected class and add the class class to the selected link
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
//hide the content and show the progress bar
//$('#content').hide();
$('#loading').show();
//run the ajax
getPage();
//cancel the anchor tag behaviour
return false;
});
});
function pageload(hash) {
//if hash value exists, run the ajax
if (hash) getPage();
}
function getPage() {
//generate the parameter for the php script
var data = 'page=' + encodeURIComponent(document.location.hash);
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//hide the progress bar
$('#loading').hide();
//add the content retrieved from ajax and put it in the #content div
$('#content').html(html);
//display the body with fadeIn transition
$('#content').fadeIn('fast');
//reapply styles?
//apply syntax highlighting. this works
SyntaxHighlighter.highlight();
//relaod processing sketch, currently displays nothing
Processing.loadSketchFromSources($('#processing'), ['mysketch.pde']);
}
});
}
This the ajax-loaded content:
<!--ajax'd content-->
<??>
<h2>code</h2>
<pre class="brush: php">
$last_modified = filemtime("header.php");
echo("last modified: ");
echo(date("m.j.y h:ia", $last_modified));
</pre>
<script type="application/processing">
</script>
<canvas data-processing-sources="mysketch.pde" id="processing">
</canvas>
</div>
</body>
</html>
<??>
So, let's analyze what usually happens when you include an (external or internal) Javascript code: It will automatically execute only the code that is available in the global scope. "Good" scripts will only add one command to the global scope which will then execute the initialization code somewhere in a function/method.
All you need to do is view the external Javascript file and find out what is being executed from the global scope. There is no general answer to that ... some scripts use an object and call its init() method ... but that is totally subject to the imagination of the developer.
If you have javascript that needs to trigger, you MUST add this to the head element:
var head = document.head || document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.innerHTML = "your AJAX-obtained js code";
head.appendChild(script);
The same trick goes for CSS. Add a element to the head with your CSS declarations as innerHTML. So: make sure to preprocess your AJAX response and split out the JavaScript and CSS elements, then add those to the document header. It's probably easier to make your response a JSON object along the lines of:
{
html: "<html>string<goes>here</goes></html>",
scripts: ["url1","url2","url2",...],
style: ...
}
and then parsing that JSON for the html (which you use as innerHTML for a new document.createElement("div") or something, and then append wherever it needs appending), the scripts (which you turn into elements for HEAD insertion) and the style declarations (which you turn into elements for HEAD insertion).
(On a functional note, your example AJAX response looks like it has PHP code in it. I have no idea what you're using it for, but that looks like a bad response)
Just incase anyone stumbles upon this:
If you have processing.js already loaded, simply call Processing.reload() in your AJAX success/complete function.
Perhaps you already have an element with id="processing" on your page. In that case $("#processing") will only return the first one. If that is the case, change the id or use a class instead.
The other option, which I don't recommend, is to use $("[id=processing]"). That will return every element on the page with id="processing". But, don't use it. Use unique ids in your page, or switch to using classes, whichever works best for you.
I have a list of videos and a video player (div container). Need to show a video in the div container when a link is clicked. The video codes is given by a third party so I want to created a conditional statement to check what is clicked based on it's id, but is not working at all! I am pretty sure it is some syntax missing:
<script type="text/javascript">
function showVideo()
{
if(document.getElementById == videoA)
{
alert("videoA")
}
if(document.getElementById == videoB)
{
alert("videoB")
}
}
</script>
--------------------
Video A
Video B
You need to pass in the "this" value:
Video A
or:
Video A
Then in the handler:
function showVideo(anchor) { // assumes you used "this", like the 1st example
var videoId = anchor.id;
//
// ... show the video or whatever ...
//
}
You need to call the getElementById and pass in the id of the element as a parameter:
if(document.getElementById("videoA"))
The HTML you've included actually have the id misspelled
Video A
Video B
should be
Video A
Video B
The way you've structured your code will show an alert for both elements. If you want the id of the element clicked, you will have to get it from the Event object and do a comparison on that basis.
document.getElementById("videoB")
You want to actually call the getElementById function and pass in the ID as a paramater.
The current way returns:
document.getElementById
>>function getElementById() { [native code] }
So you are actually comparing that function pointer to a variable videoA(which doesn't actually seem to exist in your code).
However judging by your application, I'd actually attach an onclick handler to see which one was clicked.
Video A
and in your javascript:
function videoEvent(videoLink){
// videoLink is now the ahref element
}
If that's really the code you're using, it's not working because you have a typo in it: your HTML declares two IDs, one called vidoeA and the other called vidoeB, whereas your Javascript is testing for the correct spelling.
(You also need to put the ID name in quotes in your JS).
What you actually want is something like this:
HTML
Note: Your ID's were spelled incorrectly in your question.
Video A
Video B
JavaScript
function showVideo(elem) {
if(elem.id == "videoA") {
alert("videoA")
}
if(elem.id == "videoB") {
alert("videoB")
}
//or better yet, just:
//alert(elem.id);
return false; //Stops you from following the link.
}