Add protocol to href value - javascript

I have added an editor and user can enter anything they want, then I show that entered text under message card, so if user has entered a link like Click here & its HTML part is Click here so when show this under message card and click on click here then its not redirecting to google.com it goes to http://my-website.com/google.com, its because href value don't have any protocol, so how I can add protocol to its value and there could be multiple links in single message, some could have protocol and some not.

You just need to loop over the <a> links after you have added the HTML from editor to your message card and check the protocol of each anchor link. If there is no protocol then add one to them.
$('#messageCard').find('a').each(function() {
//get the href value of each anchor element
var hrefValue = $(this).attr('href');
//use regular expression to check if the href contain http:// or
//https://. If not then add http://
if (!hrefValue.match(/^[a-zA-Z]+:\/\//))
{
$(this).attr('href','http://' + hrefValue);
}
});

It may not be a nice idea to let user to enter HTML code in the editor. But if you insist to do so, you may try
$(function() {
$('a').each(function() {
if (!$(this).attr("href").startsWith("http")) {
$(this).attr("href", "http://" + $(this).attr("href"));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click here

Related

I don't want the user to get the file directly from the url

For example:
url(`https://example.com/file.exe`)
If a user visits this website directly, the user will be redirected to https://example.com/getfile.html
but allow the user to get the file if the user gets the file from <a> tag of https://example.com/getfile.html
You can achieve this by removing href attribute in anchor tag and adding onclick function to the anchor tag. In onclick function send some parameter in url to get that value in your html page when user visits the page.
Click here to know how to send parameter in url.
Click here to know how to get post parameter from the url .
Still you have any confusion, you can comment your questions to this answer.
If you are using php you can get post parameter from url in a single line of code by using $_REQUEST["your post parameter name"];
I am adding a simple example for this to achieve with simple html and jquery.
with jquery document.referrer method on document ready(when user opens a page), you can get the previous url of user visited. like bellow example. for this you need to include jquery in your page by following line inserting in your page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
console.log(document.referrer);
if(document.referrer == "your url") {
your code to allow user if comes from the url you mentioned //user will get download button or you can write direct download option;
} else {
window.location = "some url"; //you can redirect user to specific url
}
});
<script>

How do I add an anchor-tag to window.location?

I want to use that code here to reload the current page a user is on
<a href="javascript:window.location.href=window.location.href">...
And additionally I want the user to jump to a given anchor-tag #berechnen - how would I do that in that case?
I tried with something like so
<a href="javascript:window.location.href=window.location.href+#berechnen">
But of course that doesn't work. Do I need to save the window-location to a variable first and then add the #berechnen -string to it and then href to that variable?
In head:
<script type="text/javascript">
function redirectToAnchor(anchor) {
// We remove previous anchors from the current URL
var redirectToURL = document.URL.replace(/#.*$/, "");
redirectToURL = redirectToURL + anchor
window.location.href = redirectToURL;
window.location.reload(true)
}
</script>
Then:
<a href="javascript:redirectToAnchor('#ANCHOR')">
Personally I really dislike abusing the anchor tag by replacing its default behavior with JavaScript. By doing this, you break things like being able to open the link in a new tab, copying the link or bookmarking it.
One way you can keep this behavior and still reload the page after a click, is by adding the fragment to the href as you would do normally and in addition, you bind a JavaScript event that reloads the page when it is clicked. In that case you can simply use the href attribute to get the URL, and after you set the url, you reload the page. In the example below if the anchor has a force-reload class, it will also reload the page if you click on the anchor.
document.addEventListener('click', function(e) {
if (e.target && e.target.classList.contains('force-reload') && e.target.nodeName === "A") {
e.preventDefault();
window.location = e.target.href;
window.location.reload();
}
});
Click here

hide actual url in status bar when a link or actionlink is mouseovered or clicked [duplicate]

How can I hide URL from displaying when mouse hovers on a hyperlink?
Hyperlink
How can I hide URL from displaying in browser's bottom status bar when mouse hovers?
Don't put the URL in the href (or keep it href="#") and attach a JavaScript function to the onclick event which puts the actual link in the a element. This way you won't see the actual URL when hovering over the link but the link will be inserted when the user actually clicks.
This way you can easily hide url when mouse hover on hyperlink.
Simply add one id on anchor link.
HTML
<a href="url" id='no-link'>Hyperlink</a>
Jquery code
$(document).ready(function () {
setTimeout(function () {
$('a[href]#no-link').each(function () {
var href = this.href;
$(this).removeAttr('href').css('cursor', 'pointer').click(function () {
if (href.toLowerCase().indexOf("#") >= 0) {
} else {
window.open(href, '_blank');
}
});
});
}, 500);
});
Here is demo link https://jsfiddle.net/vipul09so/Lcryjga5/
you technically have window.status to make custom status bar messages. you can set it during an "onmouseover" event for that element and set the window.status to a blank string.. thats how we did it a long time ago however..
browsers these days prevent the modification of the status bar by default (as far as i know, firefox prevents it). so there is no guarantees as to this approach will do anything at all.
<button class="class" onclick="window.location.href='https://stackoverflow.com'">Visit StackOverflow</button>
OR
<button class="class" onclick="window.location.replace('https://stackoverflow.com')">Visit StackOverflow</button>
Just use onclick="location.href='#'"
just remove href attribute from a element. :)

Change link color onclick without preventDefault()

I need change the color of the link if clicked.
If I use event.preventDefault(); color is applied permanently but the link doesn't work, then the uri isn't passed and then I can't use $_GET['route'] since I using mod_rewrite to redirect all uri's to this $_GET var. ^(.*)$ index.php?route=$1
If i don't use the event.preventDefault the link works and the section changes, but the addClass is only applied WHILE i'am clicking, then dissapears...
How I can get both behaviours ? Be able to pass the URI (HREF), and to permanently change the color onClick ?
html:
Section
css:
.active { color: #f00; }
Jquery:
$('a').on('click', function(event) {
//event.preventDefault
$(this).addClass("active");
});
You can try this in doc ready there is no need to specify any .click() event:
try the fiddle:http://jsfiddle.net/cmwt8/
$(function(){
var url = window.location.href; // url should be this way 'http://aaa.com/page/section'
var link = url.substr(url.lastIndexOf('/') + 1); // then you get here 'section'
$('[href*="' + link + '"]').addClass("active"); // if found add the class
});
You dont need to do any JavaScripting. You just need the following CSS
a:visited { color: #f00; }
Edit. If you only want to target specific links to be highlighted, add a class to the <a> link ie
HTML
<a class="sticky" href="./section">Section</a>
CSS
a.sticky:visited { color: #f00; }
That way, only the hyperlinks you want to stay sticky will have the colour applied
You can't do it because after you've been redirected to a page. all objects classes will reset.
but you can put this on your $(document).ready()
var page = window.location.pathname.split('/').pop();
$('a[href$="' + page + '"]').addClass('active');
Now what this does is as the page load example you have
test
as the page load. The page will get your last url ex. www.mysite.com/hello.php
and will find an a will matching url and add certain class.
You can not do this because its natural behavior of click.
if you use preventDefault() that means you are forcing natural behavior to work as per your rules.
anyways you can still have some alternatives.
$('a').on('click', function(event)
{
var href = $(this).attr('href');
event.preventDefault
$(this).addClass("active");
window.location = href;
});
now at this point your redirection will come to action so you don't have way to get if link color is already been changed on previous click call so session can help you.
Inside click event make ajax call and just set session variable now after page redirect check for session that you have set during ajax call then add class if session already there.
Try using
$('#elementID').on('click', function(event) {
event.preventDefault();
$(this).addClass("active");
window.location.href="./section";
});
And update the href of anchor tag as "#". i.e.
<a href="#"

How to show confirm when browser window got closed or navigated to another website in JS

As the title says ....
Sorry that some ppl got question wrong...
I want to show confirmation on these cases only:
1.Browser window is closed.
2.There is a redirect to different domain
thanks
By using the onbeforeunload event:
window.onbeforeunload = function() {
return 'Are you sure you want to navigate away from this page' ;
};
The first question has already been very well covered.
Alerts when navigating away from a web page
The second part is more troublesome. You won't get anything in the onbeforeunload event that tells you which link was clicked on to trigger it.
If you wanted to detect which link caused the close you'd have to attach some script to each link's onclick event. You'd also have to remove the href from the link and store it somewhere, you could do it like this using jQuery:
<script>
$(window).load(
function () {
$("a").each(function () {
$(this).data("url", $(this).attr("href")).attr("href", "#").click(
function () {
var destination = $(this).data("url");
// do something to check the domain, I'm just checking the whole url
if (destination == "http://norman.cx/photos/") {
alert("Not navigating to: " + destination);
} else {
alert("Navigating to: " + destination);
window.location.href = destination;
}
return false;
}
);
});
}
)
</script>
test
msft
This gets the href for each link, stores it against the link using data() and sets the link's href to "#". It then attaches a click event to each link that retrieves the url from data() and does something with it.
You could do it the other way, conditionally change the href and add the click event only on links that where on another domain.
Whether that would be a good idea or not is another question. It is at the very least an unusual thing to find yourself doing.
<body onunload="doYourThing();" >

Categories