Add anchor to links using jquery - javascript

I'm new to javascript.
Need to remove any existing anchors (eg: #page33) add other anchor (eg: #page1) to all links in a list dynamically (client side) with javascript or jquery:
Initial html (from server):
<ul id="lang_menu">
<li>English</li>
<li>Tamil</li>
<li>Sinhala</li>
</ul>
this should behave like (replace #page33 with #page1 at client side):
<ul id="lang_menu">
<li>English</li>
<li>Tamil</li>
<li>Sinhala</li>
</ul>
This is where I need this Developing Website
Please help me. Thanks in advance...

Try this way:-
$(function () {
$('#lang_menu li a').attr('href', function (_, oldHref) {
return oldHref + "#page1";
});
});
Demo
For your updated question you can try something like this:
using regex to replace the #part from the url.
$(function () {
$('#lang_menu li a').attr('href', function (_, oldHref) {
oldHref = oldHref.replace(/\#(.*)/g, "#page1");
if(oldHref.indexOf('#') == -1)
oldHref += "#page1";
return oldHref;
});
});
Demo2

If you are dealing with a lot of DOM elements its less expensive to add the anchor lazily.
jQuery("a").bind("click", function(e) {
e.preventDefault();
document.location = jQuery(this).attr("href") + "#page1";
});

Related

Removing an href value, if it exists using jquery

What would the best way to remove an href that has a specific value using jquery if it is found in the DOM.
$(document).ready(function () {
$('a').each(function () {
var hrefValue = $(this).attr("href")
if (hrefValue == '/remove/thehrefvalue?when=now') {
//remove only a href containing this specific value
}
});
});
Kind regards
Instead of iterating through every a, you can iterate through only as which have that particular href attribute by altering the selector string:
$('a[href="/remove/thehrefvalue?when=now"]').remove();
$('a[href="/remove/thehrefvalue?when=now"]').remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
now
now
notnow
now
(Not entirely sure what you're looking for. If you wanted to remove the <a>s, use the code above - if you wanted to remove the attributes but leave the <a>s alone, use removeAttr('href') instead of .remove())
$(document).ready(function () {
$('a').each(function () {
if ($(this).attr("href") == '/remove/thehrefvalue?when=now') {
$(this).removeAttr("href");
}
});
});

Click event on a link with a unique id

On a page I have links, by clicking them, it deletes an element. This is my code:
Delete input
Delete input
and so on. As you can see, the links differs with ids, so there can be hundreds links with unique ids. I need to remove closest li element to them. I do it in a such way:
$(document).ready(function () {
$('#link0').click(function (e) {
e.preventDefault();
$(this).closest('li').remove();
})
});
It works for id="link0"
I tried to put a numerical part of id into a variable i by doing this:
var i = 0;
$('#link0' + i).click(function (e) {
e.preventDefault();
$(this).closest('li').remove();
})
but I can't figure, how to make it work and how should I increment i(where should I put in the code i++). Any help would be appriciate. Thanks!
You can use classes instead of ids...
You can do it like this:
$(document).ready(function() {
$('.remove-existed-field').on('click', function(e) {
$(this).closest('li').remove();
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li>Delete input</li>
<li>Delete input</li>
Hope this helps!
You could use the starts with selector.
$('[id^=link]').click(
It will target all the elements whose id start with link
If you want to process each link a then you could do it on class instead.
Also you can get id of the clicked link if you really need it.
$(document).ready(function () {
$('a.remove-existed-field').click(function (e) {
e.preventDefault();
// $(this).attr('id');
$(this).closest('li').remove();
});
});

How to keep active class when changing pages

I am trying to add an active class to nav item, depending what page your on. I am using this script:
<script type="text/javascript">
$(document).ready(function () {
$("#side-bar a").click(function () {
var id = $(this);
$(id).siblings().find(".active").removeClass("active");
$(id).addClass("active");
localStorage.setItem("selectedolditem", id);
});
var selectedolditem = localStorage.getItem('selectedolditem');
if (selectedolditem !== null) {
$(selectedolditem).siblings().find(".active").removeClass("active");
$(selectedolditem).addClass("active");
}
});
</script>
See full jsfiddle here: https://jsfiddle.net/ebo7hLo9/
It adds the active class, but it loads a new page, it disappears. What am I doing wrong?
https://jsfiddle.net/ebo7hLo9/10/ - here's a fiddle!
$(document).ready(function () {
$("#side-bar a").click(function () {
var id = $(this);
$(".active").removeClass("active");
$(id).addClass("active");
localStorage.setItem("selectedolditem", $(id).text());
});
var selectedolditem = localStorage.getItem('selectedolditem');
if (selectedolditem !== null) {
$("a:contains('" + selectedolditem + "')").addClass("active");
}
});
Your code was having issues remembering what element to grab. I think it's due to the web storage API's unfamiliarity with objects. Instead I got the text from the element that was selected, stored it in localStorage and on page load matched it with the correct element. Also there was part of your code that was dealing with finding the class "active" within the siblings() of the selected element and removing it. That complex of code is largely unnecessary. I replaced it with the class selector $(".active")
I didn't change this in the code, but I'd advise against using localStorage in favor of sessionStorage so that the storage will clear itself on tab/browser close.
For more info take a look at this previous stackoverflow post: Storing Objects in HTML5 localStorage
Here is a possible solution: https://jsfiddle.net/6yyLpma1/
$("#side-bar a").click(function () {
var id = $(this);
$('#side-bar').find(".active").removeClass("active");
$(id).addClass("active");
localStorage.setItem("selectedolditem", id);
});
Instead of $(id).siblings() use $('#side-bar'). Use the same logic in other location.
Using data elements and a delegate function: https://jsfiddle.net/ebo7hLo9/12/
HTML
<span id="delegateAnchor">
<div id="side-bar">
<ul>
<li>Home</li>
<li>Who we are</li>
<li>Services</li>
<li>What to expect</li>
<li>Representative clients</li>
<li>Success stories</li>
<li>Current litigation</li>
<li>What if you could not be a doctor?</li>
</ul>
</div>
</span>
Javascript
$(document).ready(function () {
$('#delegateAnchor').on('click', '#side-bar a', function() {
var $this = $(this);
var linkId = $this.data('desc');
$this.closest('ul').find('a').removeClass("active");
$this.addClass("active");
localStorage.setItem("menuSelection", linkId);
});
var selectedLinkId = localStorage.getItem("menuSelection");
if (selectedLinkId !== null) {
$('#side-bar a[data-desc="'+ selectedLinkId +'"]').trigger("click");
}
});

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;
});
});

Adding CSS Class using jQuery

Below I have included the jquery code I am using to add a css class to the link in the side column that equals the active url, but it's not working, and at some point it did.
Link: http://www.liquidcomma.com/portfolio/project/TSF_Robot_Ad/1/
<script type="text/javascript">
$(document).ready(function(){
$("ul.right_submenu > li > a").each(function() {
if ($(this).attr("href") == location.href)
{
$(this).addClass("CurrentProject");
});
};
</script>
Well, besides that code missing braces and parens it can be done much simpler:
$(function(){
$("a[href^='" + location.href + "']").addClass("CurrentProject");
});
You have unclosed braces in your script:
$(document).ready(function(){
$("ul.right_submenu > li > a").each(function() {
var a = $(this);
if (a.attr('href') == location.href) {
a.addClass("CurrentProject");
}
});
});
and you could rewrite your script like this:
$('ul.right_submenu > li > a[href=' + location.href + ']')
.addClass('CurrentProject');
Following your link, my location.href goes to http://www.liquidcomma.com/portfolio/project/TSF_Robot_Ad/1/ but your project link in the page points to http://www.liquidcomma.com/portfolio/project/trade_show_fabrications/1... that will make attr('href') != location.href.
In the other links, location.href will be ending with a slash whereas the link's href will not.
You should use something else to match your project other than the href attribute, if you expect it to change in the future (and it probably will).

Categories