select current link - javascript

how can i select the current link via jquery if I have a div like this:
<div id='navigation'>
<a href='users/home'>home</a> |
<a href='projects/browse'>home</a>
<a href='discussions/browse'>home</a>
<a href='search/dosearch'>home</a>
</div>
Note I've tried:
$(document).ready(function(){
$("#navigation a").click( function(event)
{
var clicked = $(this); // jQuery wrapper for clicked element
// ... click-specific code goes here ...
clicked.addClass('selected');
});
});
But when I click on a link it selects a link and adds the class .selected but it reloads the page in order to navigate to a page and then it all disappears. Any tips?
Thanks

This should work:
$(document).ready(function() {
var loc = window.location.href; // The URL of the page we're looking at
$('#navigation a').each(function() {
if (loc.indexOf(this.href) !== -1) { // If the URL contains the href of the anchor
$(this).addClass('selected'); // Mark it as selected
}
});
});
It basically loops over the navigation items, and if the URL of the current page contains the href of the anchor, it adds the class selected to the anchor.

Yep, take the event from your click() callback arguments and use e.preventDefault(); (see there).
Or return false.
Or add a target='_blank' attribute to your links so that they open the link in some other page or tab, if you still want the link to be opened by the browser somewhere.

$(document).ready(function(){
$("#navigation a").click( function(event)
{
var clicked = $(this); // jQuery wrapper for clicked element
// ... click-specific code goes here ...
clicked.addClass('selected');
return false;
});
});
Don't forget to return false!

Related

Page fadeOut when links are clicked, except mailto: links

in the below code, I am fading out any page, and then fading in the new page, when any tag is clicked. However, there are certain instances where we don't want to fade the page out on click, for example, when an tag is set to open externally via target="_blank". The code below reflects this and is working successfully.
However, one thing I'm not sure how to achieve, is to prevent the fade out when a link contains a mailto: reference, as obviously this is designed to open a mailing client window. Therefore I don't want the page to fade out?
Thank you.
$(window).bind("pageshow", function(event) {
if (event.originalEvent.persisted) {
window.location.reload();
}
});
(function($) {
if (window.history) {
$(window).on('popstate', function() {
$("body").show();
});
}
// When links are clicked
$(document).on("click", "a", function() {
var $link = $(this);
var $href = $link.attr("href");
var $target = $link.attr("target");
// If link exists
if ($href) {
// Fade out all links unless set to open in external window target="_blank"
if ($target !== "_blank") {
$("body").fadeOut(250, function() {
history.pushState($href, null, null);
window.location.href = $href;
});
return false;
}
}
});
// On page load, fade in
$(document).ready(function() {
$("body").fadeTo(250, 1);
});
}(window.jQuery));
a very elegant way to do this is to use the awesome power of the css attribute selector and pass the validation so you only need this:
$(document).on('click','a[href]:not([href^=mailto],[target="_blank"])',function(){
$("body").fadeOut(250, function() {
history.pushState(this.href, null, null);
window.location.href = this.href;
});
return false;
})
this is where the "magic" happens: a[href]:not([href^=mailto],[target="_blank"]) (UPDATED to include the "has href" clause
I only select links that the href does not start with mailto and do not have target="_blank"
more on attribute selectors: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
Simply check the link url:
if($href.indexOf('mailto:') === 0){
//the url starts with mailto:
//it is an email link
}
More specific to your usecase, extend the if statement where you check for _blank:
if ($target !== "_blank" && $href.indexOf('mailto:') !== 0) {
//...
}
For a link that contains a mailto: reference just change this part in your code
if ($href) {
with this
if ($href && $href.indexOf('mailto:')!==-1) {
Alternatively check this fiddle demonstrating the usage of :not. In your case don't forget to use event.preventDefault() for the mailto links from opening mail client window.

javascript jquery accessing the element being clicked

I've got the following list of semibuttons loaded using javascript:
var html ='<ul class="nav well-tabs well-tabs-inverse mb10" id="users">';
html +='<li class="active"><a id="'+this.my.user+'" data-toggle="tab_'+self.my.id+'" class="pestaƱa">'+this.my.user+'</a></li>';
var users = this.my.community_users;
for (i=0;i<users.length;i++) {
if (users[i].user != this.my.user)
html +='<li><a id="'+users[i].user+'" data-toggle="tab_'+self.my.id+'" class="pestana">'+users[i].user+'</a></li>';
};
html +='</ul>';
$(html).appendTo("#Dashboard");
Note, that the first item in the list is active. I am getting something like this:
Ok, now i code he onclick event to do something when a button is clicked:
$(document).on('click', 'a[data-toggle=tab_'+self.my.id+']', function(e){
// whatever here
});
What I need now is to set active the tab being clicked and set inactive the tab that was active. How can I access both elements to addclass and removeclass active?
You could use following logic:
$(document).on('click', '#users li:not(.active)', function () {
$('#users').find('li.active').add(this).toggleClass('active');
});
Something like this might work. Basically remove the .active class from everything but the element you clicked on. The add the .active class to the element clicked on.
$(document).on('click', 'a[data-toggle=tab_'+self.my.id+']', function (e) {
$('a[data-toggle=tab_'+self.my.id+']').not(this).removeClass('active');
$(this).addClass('active');
});
I would remove the 'active' class from all the list items first, then add it back to just the only that was clicked.
$(document).on('click', 'a[data-toggle=tab_'+self.my.id+']', function (e) {
$('#users .active').removeClass('active');
$(this).addClass('active');
});

Generate url only when anchor is clicked

Is it possible to assign url to the an anchor only when it got clicked?
Token Link
When the anchor got clicked, it will go to http://example.com/token=xxxxx/
I want to generate token only when it got clicked.
If possible, How?
thanks
you can handle the event and change the href like this.
$("a").on("click", function() {
$(this).attr("href", $(this).attr("href") + "/token=xxxx");
});
you can also directly navigate the user to a different url, without changing.
$("a").on("click", function(ev) {
document.location.href = "//something-different.com";
ev.preventDefault();
return false;
});
Opening the link in another window using jQuery
$(document).ready(function () {
$(".thisClass a").on("click", function(e){
e.preventDefault(); // this prevents going to the original url or default behavior
var changedLink = $(this).attr("href", $(this).attr("href") + "/token=xxxx");
var newUrl = $(changedLink).attr('href');
window.open(newUrl, '_blank');
});
});
// Here is a way to do it with Plain Javascript - i did not test it on all browsers but worked with chrome for example.
// goes in a script.js or in script tags under the </body> element
function changeTheLink() {
event.preventDefault();
var aLink = document.getElementById('theLink');
var theOldLink = aLink.getAttribute("href");
aLink.setAttribute('href', theOldLink + "/token=xxxx");
var theNewLink = aLink.getAttribute("href");
window.open(theNewLink, "_blank");
}
// here is the HTML you owuld have to add an id and an onclick attribute to use this code
<div class="thisClass"><a href="http://thiswebsite.com" id="theLink"
onclick="changeTheLink()">Here is a link</a></div>

Toggle one anchor link at time with Jquery

Would like to toggle my active class, so when I click on one link on the page, only one link is active with the class at a time, through out my page as I click on any of the links. Could someone help me come up with a feasible solution adding to my code?
JavaScript
//Global definition
var activeState = $(".category-tree-with-article .article-list > li > a");
activeState.on('click', function (e) {
e.preventDefault;
// For class changes
activeState.toggleClass('active');
});
CSS
.active {
font-family:'MaxPro'
}
remove the class on all the other links and add the class on the clicked one
var activeState = $(".category-tree-with-article .article-list > li > a");
activeState.on('click', function (e) {
e.preventDefault;
activeState.removeClass('active');
$(this).addClass('active');
});
If you only want to do the current one then change -
activeState.toggleClass('active');
to this -
activeState.removeClass('active');
$(this).toggleClass('active'); // can still turn on and off on this element
Don't use toggle in this case
var links = $('.selector-to-your-links');
links.on('click', function(e) {
var link = $(this);
link.addClass('active');
links.not(link).removeClass('active');
return false; // I like this better than e.preventDefault() as it also does e.stopPropagation()
});

Find link from closest li and open it in a new page - Javascript

I have a submenu divided in two parts:in the right side a li which contains a link and in the left side an icon for each li.
Icons use a css class,called 'submenubtn'.I want to make a javascript function which takes the link from the closest li,assign to that icon,and when that icon is clicked,the link should be open in a new tab.
I hope I was clear enough,please ask me anything you didnt'n undertand.
here is the code i have until now:
$(document).ready(function() {
$("body").on("click", ".submenubtn", function() {
var link = $(this).find("li").attr('href');
//window.alert(link);
window.open(link)
});
});
link returns "undifined".
I don't know how much this will help,but the html page:
<?Menu?>
<div id="<?$_name?>" class="atk-menu atk-menu-vertical atk-popover">
<ul>
<?Item?>
<?MenuItem?>
<li id="<?$id?>" class="<?$class?>"> <i class="<?$icon?>"></i><?label?>MenuItem<?/?></li>
<?/MenuItem?>
<?/?>
<?$Content?>
</ul>
</div>
<?MenuSeparator?><?/MenuSeparator?>
<?/?>
EDIT I solved the problem..see in my answer the solution
Use window.location.href = link;
and closest() function of JQuery to get what you want
To open it on a new window add window.open(link, '_blank')
i think using data tags is the solution
here the soure: http://api.jquery.com/data/
new li html:
<li data-url="HERE THE URL!"/>
your new jQuery:
$(document).ready(function() {
$("body").on("click", ".submenubtn", function() {
var link = $(this).closest('li').data('url');
//window.alert(link);
window.open(link)
});
});
li element cannot contain href attribute, you can give your li a data attribute such as:
<li data-href="your url here"></li>
then you can use:
$(document).ready(function () {
$("body").on("click", ".submenubtn", function () {
var link = $(this).closest('li').data('url');
window.open(link, '_blank');
});
});
find() used to find the descendants of your element which is not applicable in your case since your anchor is the child of your li element.
So you need to use closest() to traverse up the DOM tree and get the closest parent li instead.
Try to use:
$(document).ready(function () {
$("body").on("click", ".submenubtn", function () {
var link = $(this).closest('li').find('a').attr('url');
window.location.href(link);
});
});
Problem solved
I managed to solve this...it was pretty simple.
$(document).ready(function() {
$(".submenubtn").click(function() {
a = $(this).closest('a').attr('href');
window.open(a);
return false;
});
});

Categories