Mapping href value with page urls - javascript

I have few anchor tags inside a div and I need to retrieve the href values of all anchor tags.
For example
<div id="sample">
<ul>
<li>Location1</li>
<li>Location2</li>
<li>Location3</li>
<li>Location4</li>
</ul>
</div>
Assuming I am in /location1, the li that has a href="/location1" should have a separate background color, say for example red. If I am in /location2 the corresponding li should have the same red color.
I am trying to retrieve the page url first and then store it in a variable.
var pageurl = (window.location.pathname);
But not too sure on how to retrieve the href and then map it based on the page urls.

You do something like this:
// Get the active link first
var $links = $('#sample a').filter(function() {
return this.href && this.href == location.pathname;
});
// Highlight the current li having the link
$links.closest('li').addClass('active');
In the active class set whatever style you want to apply.

This is jQuery code, need to add jQuery library to work. It will work on page load
jQuery(document).ready(function(){
var url=document.URL.split('?')[1];
if(url == undefined){
url = '';
}
if(url != ''){
url = '#'+url;
jQuery(url).trigger('click');
}
var url=document.URL.split('?')[1];
if(url == undefined){
url = '';
}
if(url != ''){
// do here what you want to do
}
}
);

$(document).ready(function(){
$('#sample ul li a').each(function(e){
var href = $(this).attr('href');
// do something with href
});
});

Related

compare url to text in variable

I have a variable called links that stores any URLs that have been visited previously.
I need to match the URLs on the page with the results from the variable. If they match assign the class "visited" to just those links.
So for example if my page has:
<a href="link1.html">
<a href="link2.html">
<a href="link3.html">
<a href="link4.html">
<a href="link5.html">
and the links variable has:
link1.html
link3.html
link4.html
In this case like to add the class "visited" to the links that are stored in the variable link1.html, link3.html and link4.html in this case. There are loads of links with all sorts of text. These ones are just for a simple example.
This is what I have so far:
$(document).ready(function() {
$('#rightbox li a').each(
function(intIndex){
var links = $(this).attr('href');
console.log(links);
$.ajax({
url: links,
type:'HEAD',
error: function() { },
success: function() {
var visited = (links)
$("#visitedLinkContainer").append(visited);
$(this).attr('href').addClass("visited");`
// I tried this but it adds visited to everylink which I knew would, but I don't know what to put here`
}
});
});
});
This is for a personal project at home. I'm using local storage at the moment, but I'd prefer to do it this way if possible.
Thank you for any help received
Use the following code:
links.forEach(function(link) {
$('#rightbox li a[href="' + link + '"]').addClass('visited');
});
The jQuery selector [<attribute>="<value>"] selects elements that their <attribute> equals to <value>.
I've created an example: https://codepen.io/anon/pen/OwMbgp
html
Link1
Link2
Link3
Link4
Link5
Link2
CSS
.visited {
color: red;
}
JS
$(document).ready(function() {
// Faking that you already entered the first 2 links
var visited = ['#1', '#2'];
// when clicking it adds the class visited right away
$( "a" ).click(function() {
visited.push($(this).attr('href'));
$(this).addClass( "visited" );
});
// loop trough the visited url and find the corresponding a tags that all have the urls inside the visited variable
$.each(visited, function( index, value ) {
// this gets all links with that same value, if you don't want this you need to store something unique of the a tag or the entire element inside the var visited
var allLinks = $('a[href^="' + value + '"]');
$.each(allLinks, function() {
$(this).addClass( "visited" )
})
// this allert shows you what index and value are
alert( index + ": " + value );
});
});
Hope this helped somehow
convert this line [var links = $(this).attr('href');], to this:
var LINK = $(this),
links = LINK.attr('href');
now, after line $("#visitedLinkContainer").append(visited); put here instead of yours code:
LINK.addClass("visited");
or try this:
$("#rightbox [href='"+links+"']").addClass("visited");
for(var i=0; i<arrayOfLinksAlreadyVisited.length;i++) {
$("#rightbox li a").each(function() {
if($(this).attr("href") == arrayOfLinksAlreadyVisited[i])) {
$(this).addClass("visited");
}
//Match the href with arrayOfLinksAlreadyVisited[i]
//if true then addClass visited to this anchor tag via
//keyword this
// else do nothing
});
}
I hope the above logic will work for you.

Hide div if URL hash begins with word in Javascript

How could I hide divs that begin with id "news" but also contain a number like "news1" "news2" etc if the URL hash doesnt contain "news".
like hide if someurl.com/#events. but show any "news" div if someurl.com/news1
need in regular JS
thanks,
Try This:-
$(function(){
var url = window.location.hash;
if(url.indexOf('news') > -1){
$("div[id^='news']").hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="news1">News1</div><br>
<div id="news2">news2</div><br>
<div id="news3">news3</div><br>
<div id="event">event</div><br>
Update: (Using Pure JavaScript)
(function() {
var url = window.location.hash;
/* for testing set the hash to 'news' */
url='news';
if(url.indexOf('news') > -1){
var bodyDOM = document.body;
bodyDOM.querySelectorAll("[id^='news']").forEach(function(item, index){
item.style.display='none';
});
}
})();
<div id="news1">News1</div><br>
<div id="news2">news2</div><br>
<div id="news3">news3</div><br>
<div id="event">event</div><br>
The script hasn't been tested. It does these steps:
Looking for the word "#news" in URL. In our case, if there aren't any word.
For each div with the ID "new" or similar
Add a CSS to this div to hide it.
<script type="text/javascript">
$(document).ready(function () {
if(window.location.href.indexOf("#news") < 0) {
$("div[id^='news']").css('display', 'none');
}
});
</script>
If you put a class on all the divs you'd want this apply to, you can do this:
$(document).ready(function() {
$('.CLASSNAME').each(function(i) {
if($(this).val().indexOf('WORD_YOURE_LOOKING_FOR') > -1) {
$(this).css('display', 'none');
}
);
});
Well you can access the hash in a URL like so:
var hash = window.location.hash;
I'm not 100% clear what you want to do at that point. If you wanted to show the news1 div, you'd do this:
if(hash == 'news1') {
$('#news1').show();
}
Try this:
var hash = window.location.hash;
$('[id^="'+hash+'"').hide();

How to convert links to text using JQuery?

I try to think up function which can replace links to text. Image inside a tag should be moved to the wrapper, the original a should be removed.
JS:
var selectors = 'a.mark-video;a.sp5;a>img[alt!=""]'
selectors = selectors.split(";").join(", ");
$(selectors).each(function() {
var current = this;
if (this.nodeName == "IMG") {
current = this.parentNode;
if (current.nodeName != "A")
current = this.parentNode;
if (current.nodeName != "A")
return false;
current = $(current);
}
var wrapper = current.parent();
var new_context = $().append(current.html());
current.remove();
wrapper.append(new_context);
}
);
The problem is
1) that the image is not inserted into the wrapper
2) if it would be inserted it would not have correct position.
I am experimenting using webextensions API (Firefox addon) and I injected the code to site:
http://zpravy.idnes.cz/zahranicni.aspx
In the debugger you can see two wrappers with class="art ". I have removed the first link but image is not inserted. The second one has not been removed yet when debugger was paused after first iteraction.
I hope you can find out why the image is not appended and how to append it to the original position of the element a. I need to find out position of the element a first, and then to move the image into to correct position - that is before div.art-info.
Note: please do not change the selectors string. This is the users input from form field.
Edit:
Almost there:
function(){
if (this.parentNode.nodeName == "A")
$(this.parentNode).replaceWith($(this));
else
$(this).html().replaceWith($(this)); // error: html() result does not have replaceWith...
}
Is this what you're looking for?
https://jsfiddle.net/4tmz92to/
var images = $('a > img');
$.each(images, function(key, image) {
$(this).parent().replaceWith(image);
});
First select all the images that you want to remove the link from, then loop through them and simply replace the parent() with the image.
I have finally solved the problem:
$(selectors).each(
function(){
if (this.parentNode.nodeName == "A")
$(this.parentNode).replaceWith($(this));
else
$(this).replaceWith(
$(this).html()
);
}
);
This works similar. Novocaine suggested not to use $(this).html() but this would skip some images so I prefer to use it.

data-rel in .attr (javascript)

Trying to add a data-rel to my javascript .attr Here is the original attr:
link.attr('href',obj.images.standard_resolution.url);
Here is what I've tried:
link.attr('href data-rel="lightframe"',obj.images.standard_resolution.url);
I also tried to making all the a links include it but with no luck:
$('a').attr('data-rel', 'lightframe');
Is this even possible? if so, what would be the correct syntax to use? I had a good read at http://api.jquery.com/attr/ but did not solve my issue?
EDIT: Markup here:
function ProcessData(response){
if(response != null){
var ul = $('<ul/>');
ul.attr({'class': tag_name});
$(response.data).each(function(index,obj){
if(index == 20)
return response.pagination.next_url;
var link = $('<a/>'), image = $('<img/>'), li = $('<li/>');
image.attr({'src': obj.images.standard_resolution.url,
'width':thumb_dimension,'height': thumb_dimension});
link.attr({'href' : obj.images.standard_resolution.url,'data-rel' : 'lightcase'});
image.appendTo(link);
link.appendTo(li);
if(include_username){
$('<div class="username">'+obj.from.username+'</div>').appendTo(li);
}
if(include_caption){
$('<div class="caption">'+obj.caption.text+'</div>').appendTo(li);
}
// Append the image (and text) to the list
ul.append(li);
});
// Append the list to the given div
$(div_to_add_pics).append(ul);
// make url correlate to the next set of data
url = response.pagination.next_url;
}
};
Try
var link = $('<a/>')
link.attr({
'href': obj.images.standard_resolution.url,
'data-rel' : 'lightframe'
});
or
link.attr('data-rel', 'lightframe');

issues with replacing a div with a div dynamically

I have created an html page, (template if you will) so what I would like to do is to leave the page all on it's own and use AJAX / jQuery to propagate the div elements with other external html pages.
Is this possible ?
I have been checking around and I have yet to find the solution.
Here is a snippet of my nav list...
<div>
<ul>
<li id="n-c"><span class="dir">Cosmo</span>
<ul id="switcheroo">
<li class="first">Special</li>
<li>Mineral</li>
<li>Lateral</li>
<li>Tangent</li>
</ul>
</li>
</ul>
</div>
In my content section I have added a
<div id="contentSwap"></div>
I tried this:
$("ul #switcheroo li a").click(function(event) {
var $parent = $(this).parent();
$parent.addClass("selected").siblings().removeClass("selected");
var href = $(this).attr('href');
$.get(href, function(data) {
$('#contentSwap').html(data);
});
event.preventDefault();
return false;
});
to no avail, can someone help me?
WDH
in the end I ended up using the simplest form to achieve my result.
<script type="text/javascript">
$(document).ready(function() {
$("#switcheroo").click(function(event){
$('#contentSwap2').load('pg2.html');
});
});
$(document).ready(function() {
$("#switcheroo2").click(function(event){
$('#contentSwap3').load('pg3.html');
});
});
</script>
... and so on ...
And ultimately swapping the div id with the one that had content already, instead of using an empty tag.
WDH
I appreciate all your insight #abdullah.abcoder #ShankarSangoli and #John Hartsock
When you get the html response in the get callback it will have all the tags starting from html, head body etc. Either you will have to make sure you only send the required markup from the server or parse the markup and and get only the markup that you want to append into contentSwap div.
The other approach is to use iframe, set the iframe source to href, onload of iframe find the required element, get the markup and then append it to contentSwap div.
$("ul #switcheroo li a").click(function(event) {
var $parent = $(this).parent();
$parent.addClass("selected").siblings().removeClass("selected");
var href = $(this).attr('href');
var dIf = $("#dummyIframe");
if(dIf.length == 0){
$(document.body).append('<iframe id="dummyIframe" style="display:none;"></iframe>');
dIf = $("#dummyIframe").onload(function(){
var iFrameContent = $("#dummyIframe").contents();
$('#contentSwap', window.parent.document)
.html(iFrameContent.find('#someDivIdOrAnyOtherSelector').html());
});
}
dIf[0].src = href;
event.preventDefault();
return false;
});
$("ul #switcheroo li a").click(function(event) {
var $parent = $(this).parent();
$parent.addClass("selected").siblings().removeClass("selected");
var href = $(this).attr('href');
$('#contentSwap').load('' + href + ''); //$('#contentSwap').empty().load(''+ href +''); you may use this for make your `#contantSwap` empty and then append contents to it
event.preventDefault();
return false;
});
I hope this will works
Assuming your data is HTML, then you can do the following using jQuery replaceWith():
$('#contentSwap').replaceWith(data);
Also, you may want to only import the portion of the HTML from the data by doing the following:
$('#contentSwap').replaceWith($('#somedivElement', data));

Categories

Resources