What is the proper method for creating dynamic hyperlinks in JavaScript? - javascript

I know it's frowned upon to create links such as link text as this tricks the user into thinking it's a real link.
I have quite a few links that actually just run JS code in the browser instead of forcing page navigation, and as such I don't want to use the above and am looking for an alternative that works in all browsers and prevents middle clicking from opening a new tab/ window.
Would the following approach be satisfactory?
HTML
link text
JavaScript
$("#id_here").bind('click',(function(params){
return function(){
// do stuff here with `params`
};
})(params));

javascript: anything is bad. There isn't much difference between the two javascript: uses above. Using "#" for the href is about as bad; it adds to the history with JS off and the link is not useful. What you should do (ideally) is have the link actually work, e.g.
<a href="/an/actual/path"> ...
Then, with JS, prevent default link behavior
$("#id_here").on('click', function (e) { e.preventDefault(); });
If there is no actual path to go to, then the link should not even be exposed with JS off; you can either append it to the DOM later or just hide it with CSS (and show it with JS).

I would recommend you used another node other than <a>, such as a <div>:
<div id="jsLink" style="cursor:pointer">Click Me</div>
and jQuery:
$("#jsLink").click(function(params){
// do something
}

link text
# is here to make a link look like link
JavaScript:
$("#id_here").bind('click',function(e){
e.preventDefault();
})
e.preventDefault() does not allow browser to execute default action (like navigate to another page)

I did some playing around, and you can get some good results with hashchange:
var commands = {
foo: function() { alert("Foo!"); },
bar: function() { alert("Foo bar!"); },
baz: function() { alert("Foo bar baz!"); }
};
$(window).bind('hashchange', function() {
var hash = window.location.hash.replace(/^#/,'');
if(commands[hash]) {
commands[hash]();
return false;
}
}).trigger('hashchange');​
With the simple HTML of:
Foo
Bar
Baz​
This even works if you right click -> open in new tab or middle click!
Note that hashchange is not supported by all browsers.

Related

jQuery history usage

I have created a webpage that uses jQuery to show and hide elements. The obvious problem now arose; the back and forward browser buttons don't work anymore as everything is loaded within a single location.
I know the answer lies within jQuery History but after busting my head for several hours on their website and examples given here on stackoverflow, I still cant manage to:
A) create a history entry (I think i got this covered but not 100% sure)
B) animate the page transition with my own function (displayed beneath)
This is the website: www.grommit.nl
There are 4 sub-pages that require a history entry when called upon.
This code shows the transition of the "wordpress page". The other pages work in a similiar way. (so far I have only managed to generalize the last part of the pageload with the "LoadPageContent" function, the bit before that is different with every page)
var LoadPageContent = function() {
$(".sceneBody").slideDown(function() {
$(".aftertitle").css('width', '4em');
$(".mediacontainer").fadeTo('0.3s', 1,)
});
$("#goWordpress").click(function () {
$("#homeScene").fadeOut(function () {
$("#wordpressMessage").fadeIn(function() {
$(this).delay(300).slideUp(function() {
$("#wordpressPage, #grommitFixed").slideDown(function() {
LoadPageContent();
});
});
});
});
});
this is the function that is currently working as a previous button within the DOM. I would like this function to execute when the previous button is clicked.
var goBack = function() {
$(".aftertitle").css('width', '0em')
$(".mediacontainer").fadeTo('0.3s', 0, function() {
$(".scenebody, #grommitFixed").slideUp(function() {
$("*[id*=Page]:visible").each(function() {
$(this).slideUp(function() {
$("#homeScene").fadeIn();
});
});
});
});
};
In html5 you have something called pushstate, that you can use to tell the browser what to go back to. Check out:
html pushstate

Trigger an 'onClick' via URL, but do not visit that URL

Trying to launch a click event of .register-btn a nav item when visiting a given URL, but not allow the browser to visit that URL.
So, home.com/memberlogin would remain on home.com ( or redirect to home.com if I must ), and proceed to activate the click of a button.
This is what I have so far, which redirects nowhere as that ended up taking longer than the click event, and it also was quite messy having to load the 404, then wait, then redirect, then wait, then wait for the click event.
I would like something clean and smooth if possible.
jQuery(document).ready(function() {
jQuery(function() {
switch (window.location.pathname) {
case '/memberlogin':
jQuery('.register-btn a').trigger( "click" );
return False;
}
});
});
Probably explained it dreadfully so apologies all - the .register-btn a already exists so I can't create this element, I simply wish to trigger the click for it when visiting a URL/link. Open to suggestions but I assumed something like /memberlogin would suffice, then the link would trigger. The snag is I don't want to "visit" that URL, but use it for the trigger only.
Open to an easier way and tell me if I am asking for something that doesn't work, just figured there must be a way.
Have you tried e.preventDefault() ?
click
and the jQuery:
$('.dontGo').on('click',function(e){
e.preventDefault();
//do stuff
})
fiddle: https://jsfiddle.net/b9x7x4m6/
docs: http://www.w3schools.com/jquery/event_preventdefault.asp
A full javascript solution is (snippet updated as asked):
window.onload = function () {
[].slice.call(document.querySelectorAll('.dontGo')).forEach(function(element, index) {
element.addEventListener('click', function(e) {
e.preventDefault();
alert(e.target.textContent);
}, false);
});
// in order to target a specific URL you may write code like in reported,
// assuming the result is only one element,
// otherwise you need to use the previous [].slice.call(documen.....:
document.querySelectorAll('.dontGo[href="linkedin.com"]')[0].addEventListener('click', function(e) {
e.preventDefault();
alert('Linkedin anchor: ' + e.target.textContent);
}, false);
};
stackoverflow <br/>
google <br/>
linkedin <br/>
twitter <br/>
The querySelector let you select elements in a lot of different ways:
if you need to select an anchor with a specific href value you can write:
document.querySelectorAll('.dontGo[href="linkedin.com"]')
Remember, always, that the result of querySelectorAll is a NodeList array. You can test against the length of such array in order to get, just for instance, only the second element if it exists, like:
var nodEles = document.querySelectorAll('.dontGo[href="linkedin.com"]');
if (nodEles.length > 1) {
nodEles[1]......
}
or you can use the format:
[].slice.call(...).forEach(....
to convert the NodeList to a normal array and than apply the event listener for each element.
Yes, you may prefix the href attribute of anchor tag with an hash (#) to avoid page redirecting. But, in this case, the hash tag is used to jump in another page section and this will change your url.
Simply create a function
function theAction(){
return false;
}
Then your link will be
page name

Click all links on page containing string?

I'm trying to add a function to a toolbar Chrome extension I've made. What I'd like it to do is once a navigate to a particular page I'd like be able to push a button on the tool bar and have it "click" all of the links on that page containing harvest.game?user=123456 with 123456 being a different number for all of the links. It could be using jquery or javascript. The only catch is that the script will need to be inserted as an element to the head of the page as cross domain scripting is not allowed so no external references to a js file. I can handle the adding of the element but, I'm having no luck figuring out the actual function.
The elements containing the links all look like this:
<div class="friendWrap linkPanel">
<h5>Christine...</h5>
<div class="friend-icon">
<img src="https://graph.facebook.com/100001726475148/picture"></div>
<div class="levelBlock friend-info">
<p>level</p>
<h3 class="level">8</h3></div>
Harvest
<a class="boxLink" href="profile.game?user_id=701240"><span></span></a></div>
Something like this (I know this is a mess and doesn't work)? OR maybe something BETTER using jquery?
var rlr=1;
function harvestall(){var frt,rm,r,rld,tag,rl;
var frt=1000;
r=document.getElementsByClassName("friendWrap linkPanel");
rl=r.length;
rld=rl-rlr;
if(rld>=0){tag=r[rld].getElementsByTagName('a');
if (rl>=1 {rlr++;harvestall();}
else if (rl>=1) {tag[1].onclick();do something??? ;}
}
Something like this should work
$("a[href*='harvest.game?user=']").trigger("click");
// Using jQuery, wait for DOMReady ...
$(function harvestLinks() {
// Only create regexp once ...
var reURL = /harvest.game\?user=/,
// Create a ref variable for harvest links ...
// Use 'links' later without querying the DOM again.
links = $("a").filter(
function() {
// Only click on links matching the harvest URL ...
return this.href && reURL.test(this.href);
}
).click();
});

TinyMCE opened in jqueryUI modal dialog

When using tinyMCE in a jqueryUI modal dialog, I can't use the hyperlink or 'insert image' features.
Basically, after lots of searching, I've found this:
http://www.tinymce.com/develop/bugtracker_view.php?id=5917
The weird thing is that to me it seams less of a tinyMCE issue and more of a jqueryUI issue since the problem is not present when jqueryUI's modal property is set to false.
With a richer form I saw that what happens is that whenever the tinyMCE loses focus, the first element in the form gets focus even if it's not the one focused / clicked.
Does some JavaScript guru have any idea how I might be able to keep the dialog modal and make tinyMCE work?
This fixed it for me when overriding _allowInteraction would not:
$(document).on('focusin', function(e) {
if ($(event.target).closest(".mce-window").length) {
e.stopImmediatePropagation();
}
});
I can't really take credit for it. I got it from this thread on the TinyMCE forums.
(They have moved their bugtracker to github. tinymce/issues/703 is the corresponding github issue.)
It seems there are no propper solution for this issue yet. This is kind of a hack but it really worked for me.
Every time you open the Dialog remove the text area and re add it like following,
var myDialog = $('#myDialog');
var myTextarea = myDialog.find('textarea');
var clonedTextArea = myTextarea.clone(); // create a copy before deleting from the DOM
var myTextAreaParent = myTextarea.parent(); // get the parent to add the created copy later
myTextarea.remove(); // remove the textarea
myDialog.find('.mce-container').remove(); // remove existing mce control if exists
myTextAreaParent.append(clonedTextArea); // re-add the copy
myDialog.dialog({
open: function(e1,e2){
setTimeout(function () {
// Add your tinymce creation code here
},50);
}
});
myDialog.dialog('open');
This seems to fix it for me, or at least work around it (put it somewhere in your $(document).ready()):
$.widget('ui.dialog', $.ui.dialog, {
_allowInteraction: function(event) {
return ($('.mce-panel:visible').length > 0);
}
});

Create a dual function html Url Link?

Problem:
You have a regular set of URL links in a HTML page e.g.:
Foo Bar
You want to create a JavaScript function such that when any HTML links are clicked, instead of the client's browser navigating to that new URL "/foo/bar" a JavaScript function is executed instead (e.g. this may for example make an Ajaxian call and load the HTML data without the need to reload the page).
However if the JavaScript is disabled OR a spider crawls the site, the UTL links are maintained gracefully.
Is this possible? Does it already exist? What's the usual approach?
EDIT 1:
These are some great answers!
Just a follow on question:
If the user clicks on the back button OR forward button, this would naturally break (as in it would go back to the last physical page it was on as opposed to one that was loaded).
Is there any way (cross browser) to maintain the back/forward buttons?
(e.g create an array of links clicked and over ride the browser buttons and use the array to navigate)?
<script type="text/javascript">
function your_function() {
alert('clicked!');
}
</script>
<a onclick="your_function();" href="/foo/bar">Foo Bar</a>
If Javascript is off, the link behaves normally.
In this case, unless your_function() does not return false, the link will be followed when clicked as well.
To prevent this, either make your_function() return false, or add return false; just after the function call in your onclick attribute:
<script type="text/javascript">
function your_function() {
alert('clicked!');
return false;
}
</script>
<a onclick="your_function();" href="/foo/bar">Foo Bar</a>
Or:
<script type="text/javascript">
function your_function() {
alert('clicked!');
}
</script>
<a onclick="your_function(); return false;" href="/foo/bar">Foo Bar</a>
Using element.addEventListener()
With default anchor behaviour following click:
<script type="text/javascript">
document.addEventListener("load", function() {
document.getElementById("your_link").addEventListener("click", function() {
alert('clicked');
}, true);
}, true);
</script>
<a id="your_link" href="/foo/bar">Foo Bar</a>
Without:
<script type="text/javascript">
document.addEventListener("load", function() {
document.getElementById("your_link").addEventListener("click", function(event) {
event.preventDefault();
alert('clicked');
}, true);
}, false);
</script>
<a id="your_link" href="/foo/bar">Foo Bar</a>
Given current HTML and W3C APIs, I would go for:
<script src="linkify.js"> </script>
in the markup, with linkify.js containing something like:
window.onload= function() {
document.addEventListener('click', function(ev) {
ev.preventDefault();
var el = ev.target;
if (el.tagName === 'A') {
// do stuff with el.href
}
}, false);
};
See e.g. http://jsfiddle.net/alnitak/nrC7G/, or http://jsfiddle.net/alnitak/6necb/ for a version which doesn't use window.onload.
Note that this code uses a single listener function registered on the document object, which will act on every <A> tag on the page that doesn't trap clicks for itself.
Use an onclick attribute:
click?
The return false prevents the default behaviour, in the absence of JavaScript, however, the link will be followed.
function do_whatever (e)
{
e.preventDefault ();
// do whatever you want with e.target
}
var links = document.getElementsByTagName ("a");
for (var i=0; i<links.length; ++i)
links[i].addEventListener ('click', do_whatever);
http://jsfiddle.net/bTuN7/
All done inside script and it won't 'hurt' if JavaScript doesn't work.
If you think about AJAX, then you have to know, that googlebot tries to parse it. http://www.youtube.com/watch?v=9qGGBYd51Ts
You can code like:
$('a').click(function() {
doSomethingWithURL($(this).attr('href'));
return false;
});
JavaScript is not executed in case it's disabled or if it's some web crawler, so from my point of view this is preferable.
There's quite a few methods out there such as this:
http://www.malbecmedia.com/blog/development/coding-a-ajax-site-that-degrades-gracefully-with-jquery/
Remember, though, that by virtue of a well setup server and caching you're not going to gain yourself much performance with an Ajax Load.

Categories