compare url to text in variable - javascript

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.

Related

js How to add href + text onclick

I need to pass (using javascript) text inside span to href
<div class='tableCell'><span>information</span></div>
<div class='tableCell'><span>contact</span></div>
<div class='tableCell'><span>about</span></div>
for example when i click to about link must be example.com/tag/about/
Here is my Answer. I'm using Javascript to manipulate the DOM to add a new element with the href equal to the inner text within the span element.
I hope you find this answer helpful.
Thanks.
var spans = document.getElementsByTagName('span')
var baseUrl = 'http://example.com/tag/'
for(var i=0; i<spans.length; i++)
{
var curElement = spans[i];
var parent = curElement.parentElement;
var newAElement = document.createElement('a');
var path = baseUrl+curElement.innerHTML;
newAElement.setAttribute('href', path);
newAElement.appendChild(curElement);
parent.appendChild(newAElement)
}
DEMO
The simplest way:
$( "span" ).click(function() {
var link = 'http://yousite.com/tag/'+ $(this).text().replace(/ /, "-")+"/";
window.location.href= link.toLowerCase();
});
DEMO
http://codepen.io/tuga/pen/yNyYPM
$(".tableCell span").click(function() {
var link = $(this).text(), // will provide "about"
href = "http://example.com/tag/"+link; // append to source url
window.location.href=href; // navigate to the page
});
You can try the above code
You do not have links but span in your html. However, you can get build the href you want and assign it to an existing link:
$('div.tableCell').click(function(){
var href = 'example.com/tag/' + $(this).find('span').text();
})
Lets work with pure javascript, I know you want to use jQuery but I am really sure too many people can't do this without looking in to web with pure javascript. So here is a good way.
You can follow it from jsFiddle
var objectList = document.getElementsByClassName("tableCell");
for(var x = 0; x < objectList.length; x++){
objectList[x].addEventListener('click', function(){
top.location.href = "example.com/tag/" + this.childNodes[0].innerHTML;
});
}
Lets work on the code,
var objectList = document.getElementsByClassName("tableCell");
now we have all element with the class tableCell. This is better than $(".tableCell") in too many cases.
Now objectList[x].addEventListener('click', function(){}); using this method we added events to each object.
top.location.href = "example.com/tag/" + this.childNodes[0].innerHTML; with this line if somebody clicks to our element with class: We will change the link to his first child node's text.
I hope it is useful, try to work with pure js if you want to improve your self.
Your Method
If you always are going to have the url start with something you can do something like this. The way it is set up is...
prefix + THE SPANS TEXT + suffix
spaces in THE SPANS TEXT will be converted to -
var prefix = 'http://example.com/tag/',
suffix = '/';
$('span').click(function () {
window.location.href = prefix + $(this).text().replace(' ', '-').trim().toLowerCase() + suffix;
//An example is: "http://example.com/tag/about-us/"
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='tableCell'><span>Information</span></div>
<div class='tableCell'><span>Contact</span></div>
<div class='tableCell'><span>About</span></div>
You can adjust this easily so if you want it to end in .html instead of /, you can change the suffix. This method will also allow you to make the spans have capitalized words and spaces.
JSBIN

Click based upon value of hash on url

I'm new to working with JS/jQuery, I've been currently trying to figure out how to make this work, by trying many different ways that I've found here and on different sites, and am unable to get this working.
I have a website that has tabs, that changes a div's content when the click on the buttons in the menu. This all works fine, but I want to be able to link to each separate "page" using hash tags example.com/#tab-1
HTML:
<div class="tabWrapper">
<div class="tabContent">
<div class="label">TAB 1</div>
<?php include 'tab1.php'; ?>
</div>
<div class="tabContent">
<div class="label">TAB 2</div>
<?php include 'tab2.php'; ?>
</div>
tabWrapper looks like this after being generated
<div class="tabWrapper">
<ul class="tabs">
<li class="tab-1">TAB 1</li>
<li class="tab-2">TAB 2</li>
</ul>
JS :
// Generate tab navigation
if ($('div.tabWrapper').length != 0)
{
$('div.tabWrapper').each(function()
{
// Prepare tab output
var printTabs = '<ul class="tabs">';
var tabContent = $(this).find('.tabContent');
var tabCount = tabContent.length;
$(tabContent).each(function(key)
{
// Hide tab if it is not the first
if (key != 0)
{
$(this).hide();
}
// Get label for tab
var label = $(this).find('.label').text();
// Use a number if no label was given
if (!label)
{
label = 'Tab ' + (key + 1);
}
// Add id to tab content
$(this).addClass('tab-' + key);
printTabs+= '<li class="tab-' + key + '">' + label + '</li>';
});
// Add tabs
$(this).prepend(printTabs + '</ul>');
$(this).find('li:first').addClass('active');
});
}
// Handle click on tabs
$('.tabWrapper').delegate('ul.tabs li', 'click', function()
{
// Deny click on active element
if ($(this).is('.active'))
{
return false;
}
// Get tab id
var id = $(this).attr('class').split('-');
id = id[1];
// Display and animate new tab content
var parent = $(this).parent().parent();
parent.find('ul.tabs li').removeClass('active');
$(this).addClass('active');
parent.find('.tabContent').hide()
parent.find('.tab-' + id).animate({ opacity: 'show' }, animationSpeed);
});
Here is what I was trying to add, which I don't think is correct
function hash() {
if(window.location.hash){
var hash = window.location.hash.substring(1);
$("." + hash).click();
}
}
which I added in the js file just above
$('.tabWrapper').delegate('ul.tabs li', 'click', function()
I'm not sure how far I'm off with that code, as it doesn't seem to work at all. I just want it to see if there is a hash tag in the url, and if there is then run the click function to change the content.
I hope I explained what I was looking for clear enough. I'd very much appreciate any help with this.
Thank you.
UPDATE:
I updated the code with setInterval as per chiliNUT's suggestion, however it still doesn't appear to be working.
setInterval(hash,1000);
function hash() {
if(window.location.hash){
var hash = window.location.hash.substring(1);
$("." + hash).click();
}
}
UPDATE 2:
Still unable to get this working, anyone able to help?
Thanks.
My tip is using anchor tags as well.
Link
That will open example.com#tab1
The control on page load:
$( document ).ready(function() {
if(window.location.hash == "#tab1"){
$("#someId").click();
}
});
Why not just use anchor tags?
Button to open tab 1

Jquery mobile - Click button to add to UL

i am trying to build an application that when the user enters text into a textbox on a jquery based mobile app and clicks save it adds it to the list on the screen
so by default i won't have a list, but as the user adds an item the list should be created or if the list already exists, the new item added as a new list item.
in terms of saving it i will work on that after, for the time being i just want to dynamically append to a ul in jqm on the screen
Can someone assist with code that may help with this. it is giving me an item added saying "item undefined" however numslist is my list and txtbox is the textbox so im not sure where i am going wrong
thanks
<script>
var $txtbox = $("#txtbox").val();
var count = 0;
$("#main").live("pagecreate", function(event) {
$("#numlist").listview({create: function(event, ui) {
$("#addBtn").bind("click", function(event, ui) {
var str = "<li><a href='#'>Item " + ($txtbox) + "</a></li>";
$("#numlist").append(str);
$("#numlist").listview("refresh");
});
$("#removeBtn").bind("click", function(event, ui) {
// if (--count < 0) {
// count = 0;
// return;
// }
$("#numlist").find("li").remove();
$("#numlist").listview("refresh");
});
}});
});
</script>
Well, you can use localstorage, that way you won't need to code extra functions that save/store data.
try this:
var $lst = $('#productList');
$("#btnID").on("click",function() {
var $txtBox = $("#txtBox");
var $li = $('<li/>').html($txtBox.val());
$lst.append($li).listview('refresh');
$txtBox.val("");
});
working fiddle here: http://jsfiddle.net/REthD/21/
If I understood your question correctly, something similar to the following should work for you:
$('input[type=button]').on('click', function() {
var ul = $('#ul_id').length > 0 ? $('#ul_id') : $('<ul />', { id: 'ul_id'}).appendTo('#parent');
$('<li />').text($('#textbox').val()).appendTo(ul);
});
The first line in the event will check if the element exists, if it does, it returns that, otherwise, creates a new and appends to the specified parent element. Then, it appends a to the with the text from the textbox.
jsFiddle example

Mapping href value with page urls

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

How to Read a webpage and extract certain links using jQuery?

Its on the same domain.. both my Jquery code and the url to read.
What i want to do is first read the webpage using Jquery and then parse certain links which has "ProductDetails.php" and extract "ProductCode" from the webpage into array.
The html page may have many instances of a href="ProductDetails.php which looks like below.
<a href="ProductDetails.php?ProductCode=SMS%2D15%2DXLG%2DA7&CartID=1" class="carttext colors_productname cart-item-name">item 1 <a>
<a href="ProductDetails.php?ProductCode=SMS%dfdfde&CartID=2" class="carttext colors_productname cart-item-name">test me item <a>
I dont know if this is really possible
You would have to do something like this:
var filteredAnchors = $( document.body ).find( 'a' ).map(function( _, anchor ) {
if( anchor.getAttribute('href').indexOf( 'ProductDetails.php' ) === 0 ) {
return anchor.getAttribute('href').match( /ProductCode=(.*?)&/ )[ 1 ];
}
}).get();
filteredAnchors now should contain all product codes.
Example: http://jsfiddle.net/WgwSr/
Something like this should get you started:
$.ajax({
url: "pagetoload.html",
success: function(htmlofthepage) {
var html = $(htmlofthepage),
resultarray = []; // the array containing our final result set
// getting all of the anchor tags we want to look at
$('a[href^="ProductDetails.php"]', html).each(function () {
var t = $(this), // the anchor tag
href = t.prop('href'), // the href of the tag (eg. ProductDetails.php?...)
start = href.indexOf('ProductCode', 0),
begin = 0,
end = 0;
if (start > -1) {
begin = href.indexOf('=', start) + 1;
end = href.indexOf('&', begin);
resultarray.push(href.split(begin, end));
}
});
}
});
Use jQuerys eachfunction:
jQuery(function($){
var links = [];
$("a[href^=ProductDetails.php]").each(function(){
links.push(this.href.replace(/^.*\?/,'');
});
});

Categories

Resources