How to set class using execCommand? - javascript

Hello I have the following to set a link:
function iLink() {
var linkURL = prompt("Enter the URL for this link:", "http://");
richTextField.document.execCommand("CreateLink", false, linkURL);
This works but i want to change the class of the link, so i tried:
var linkURL = prompt("Enter the URL for this link:", "http://");
richTextField.document.execCommand("CreateLink", false, linkURL);
var listId = window.getSelection().focusNode.parentNode;
$(listId).addClass("alink");
But that didnt work, have I done something wrong with the above code or is their another way i can implement a class name?

You probably don't have jquery loaded on the page, and you don't need jquery anyway.
Try:
richTextField.getSelection().focusNode.parentNode.classList.add("alink");

Related

How to change href value using javascript?

I have a wordpress site and theme that is providing me an ability to change elements in menu widget on all pages it appears only.
So, what I want to do is to change links and names of menu elements locally on one page. I have an id's for menu li elements, 'menu-item-7062' for example and a href tag inside it with already defined link and text values.
I have already tried and injected this code snippets in after all post content:
<script type='text/javascript'> document.getElementById('menu-item-7062').href = 'new link'; </script>
I have also created a function that is triggers after onclick event:
<script type="text/javascript">
document.getElementById("menu-item-7062").onclick = function() {
document.getElementById("menu-item-7062").href="my new link";
};
</script>
Unfortunately, they didn't affect my old link. Returning to my question, what are other solutions I could try in order to change both a href link and text value? What possible mistakes I have made?
UPDATED:
Here is my anchor tag
Автоматизация технологических процессов
A tag located under the <li id="menu-item-7062">, there is my mistake.
Did you try setAttribute function
document.getElementById("menu-item-7062").setAttribute("href", "my new link");
I have successfully affected a tag by query selector:
<script type="text/javascript">
var tag = document.querySelector('a[href="https://test.etm.io/ru/services/automation/"]');
if(tag){
tag.innerHTML = "new";
}
</script>
you should try this..
var a = document.getElementsByTagName("a");
a[0].href = "www.abc.com/";
if you doesn't know index of a then you should get id of a and then set link.
This will help you to check and set href for tag "a" without "id":
const parent = document.getElementById("menu-item-7062");
if(parent.firstElementChild.localName === 'a') {
const child = parent.firstElementChild;
child.href = 'my new link';
}
OR
const parent = document.getElementById("menu-item-7062");
parent.firstElementChild?.href = 'my new link';

passing actual URL parameters to a button

I'm working on a web funnel , that i would like to track starting from step number #1 .
I'm trying to pass URL parameter for example :
https://mywebsite.com/###/######.html?subid=160445&eng_source=160445&eng_subid=null&eng_click=1d1ba0f6784b4c36918f087b616a3366
i want to pass the "subid=#" to the next destination which is button link
so it becomes:
https://landing.mywebsite.com/2scstep.html?subid=160445
or what ever "subid" was there before .
i just need some instruction from where to start adding this or what language should i work with .
Thanks A lot .
OK, lets imaging you have button on the page, which is
<a id="button" href="https://landing.mywebsite.com/2scstep.html">
Take me to new destination
</a>
If I understood you question correctly, you want change the destiantion of the button (href) so it becomes oldhref + '?subid=#'
It can be done in many techniques in javascript. Simpliest way is to install jquery, and then make smething like this
//Wait untill whole document is loaded
$(document).ready(function(){
//You now is on the page, that has url e.g. `href` + `?subid=12345`
// you got to get you subid var to javascript
//Get whole url
var currentHref = window.location.href;
//Get only params part, by splitting string by ? and taking second part
var currentHrefParamsPart = currentHref.split("?")[1];
//Now get all params to array (there can be lots of params)
var paramsArray = currentHrefParamsPart.split("&");
//Now get subid value
var subid = false; //its not known yet
paramsArray.each(function(params){
var key = params.split('=')[0]
if (key == "subid") {
var subid = params.split('=')[1]; //We got it
}
})
//Now you gotta change href attribute of the button if subid was found
if (subid) {
var $button = $("#button");
var oldHref = $button.attr("href"); //get the old href
var newHref = oldHref + "?subid=" + subid; //make new href
$button.attr("href", newHref);
}
})
It is not working code, there could be mistakes or tyopos, I wrote it to give you an idea how to achieve the result, what techiques and languages should be used.

Adding a target="_blank" with execCommand 'createlink'

I am attempting to create a mini WYSIWYG editor for a custom CMS. It has the option to add and remove links. It adds links fine, but would like to have the option to add target="_blank" to the hyperlink. Also, if possible, I would like to be able to add alt="" and title="".
At the moment this is my code:
function addLink() {
var linkURL = prompt('Enter a URL:', 'http://');
editorWindow.document.execCommand('createlink', false, linkURL);
}
Been looking around, and can't seem to find a solution. Most of the solutions I've seen say to add:
function addLink() {
var linkURL = prompt('Enter a URL:', 'http://');
var newLink = editorWindow.document.execCommand('createlink', false, linkURL);
newLink.target = "_blank";
}
But this doesn't seem to work. Any suggestions?
I was able to find a solution. Don't know if this is the right way to go, but it works. Following https://stackoverflow.com/a/5605841/997632, this is what I used for my code to work:
function addLink() {
var linkURL = prompt('Enter a URL:', 'http://');
var sText = editorWindow.document.getSelection();
editorWindow.document.execCommand('insertHTML', false, '' + sText + '');
}
Just in case anyone else is looking and stumbles upon this...
insertHTML can be frustrated if you have a bold or italic before.
I use the following approach:
var url = 'example.com';
var selection = document.getSelection();
document.execCommand('createLink', true, url);
selection.anchorNode.parentElement.target = '_blank';
I know this thread is quite old, but let me throw my 2 cents in, and maybe someone will find this useful ;)
I'm working on a WYSIWYG editor too As I found the accepted solution fails for me when I try to make a link from a selected image in FF (the getSelection().getRangeAt(0) returns the image's parent div and treats the image as it never wasn't there (this is how I see it)), here's a dirty but working (and, I think, it's turbo-cross-browser) idea I came up with (jQuery):
//somewhere before losing the focus:
sel = window.getSelection().getRangeAt(0);
//reselecting:
window.getSelection().addRange(sel);
//link:
document.execCommand('createLink', false, 'LINK_TO_CHANGE');
$('a[href="LINK_TO_CHANGE"').attr('target', '_blank');
//any other attr changes here
$('a[href="LINK_TO_CHANGE"').attr('href', theRealHref);
Is it good idea? Works like a charm. And this simplicity ^^
Since, there is no straightforward cross-browser solution, one cross-browser workaround could be programatically attaching an event handler to a inside your editor:
var aLinks = Array.prototype.slice.call(editorElement.querySelectorAll('a'));
aLinks.forEach(function(link) {
link.addEventListener('click', function() {
window.open(link.href, '_blank');
});
});
Nobody seems to mention that as per specs, the document has to be in the design mode:
document.designMode = "on";
Then the following should work:
var url = 'http://google.com';
var selection = document.getSelection();
document.execCommand('createLink', true, url);
The execCommand'createLink' does not always work. It will sometimes wrap the link text inside a link.
i.e
<a>label</a>
Resulting the html link code appearing in the document and the link not working.
in this case ues execCommand 'insertHTML'
val=``+label+``
//document.execCommand('createLink', false, val);
document.execCommand('insertHTML', false, val);

Identify links with relative path in jQuery

I wrote the below code to identify external links and then add "external" class to them. I implemented this on my site, it's working fine but there is one problem it is not working correctly for "Tabs" and "Reply to comment" options. There it's adding "external" class to them but they are local links. Let me know if there's something wrong with my code.
Link for tab is like this: Popular
and link for reply is like this: <a class="comment-reply-link external" href="/samsung-galaxy-ace-plus-s7500-how-to-root-and-install-custom-recovery-image/?replytocom=1044#respond" onclick="return addComment.moveForm("comment-1044", "1044", "respond", "420")">Reply</a>
I know that it's failing because these are not absolute links so location.host will not work for these links. Can you let me know how can I incorporate these links and add "local" class to them?
jQuery(document).ready(function ($) {
var root = new RegExp(location.host);
$('a').each(function(){
if(root.test($(this).attr('href'))){
$(this).addClass('local');
}
else{
// a link that does not contain the current host
var url = $(this).attr('href');
if(url.length > 1)
{
$(this).addClass('external');
}
}
});
Instead of getting the attribute, get the property:
var url = $(this).prop('href');
Or:
var url = this.href;
The difference is important:
> $('foo').prop('href')
"http://stackoverflow.com/questions/17130384/identify-links-with-relative-path-in-jquery#bar"
> $('foo').attr('href')
"#bar"
Also, I would use location.origin instead of location.host:
$('a').filter(function() {
return this.href.indexOf(location.origin) === 0;
}).addClass('local');
Demo: http://jsfiddle.net/q6P4W/

How can I change the href of an anchor after it has been clicked?

I have a page that pulls in data via AJAX. As well as this I have a link to download said data as a CSV file.
The problem I have is that upon I need to pass some parameters along with the click event so that the server can return the correct CSV file.
Without any processing the link looks like this:
Download Target Reports
This then fires off an ASP.NET MVC Controller action that returns the CSV. What I want to do though is pass two parameters along in the query string. Initially I thought that I could intercept the click event and add data to the query string like so:
var holder = $('.hidden-information').first();
var newOutlets = $('input[name="newoutlets"]', holder).val();
var queryDate = $('input[name="enddate"]', holder).val();
var anchor = $(this);
var link = anchor.attr('href');
link = link + "?endDate=" + queryDate + "&newOutlets=" + newOutlets;
anchor.attr('href', link);
It would seem that changing the href at this stage will not update the link in time and the URL will be as it was when it hits the server?
Is it possible to change a URL after it has been clicked or do I need to look at another method?
Thanks
You could redirect the window yourself, like this:
var holder = $('.hidden-information').first();
var newOutlets = $('input[name="newoutlets"]', holder).val();
var queryDate = $('input[name="enddate"]', holder).val();
window.location.href = this.href + "?endDate=" + queryDate + "&newOutlets=" + newOutlets;
return false; //prevent default going-to-href behavior
Or, whatever is updating those hidden fields, update the link then instead of when it's clicked, for example:
$("#someField").change(function() {
var holder = $('.hidden-information').first();
var newOutlets = $('input[name="newoutlets"]', holder).val();
var queryDate = $('input[name="enddate"]', holder).val();
$("a.black").attr("href", function() {
return "/manager/TargetResults.csv" + "?endDate=" + queryDate + "&newOutlets=" + newOutlets;
});
});
The main difference is this still allows normal click behavior to work, ctrl+click, etc.
Just rounding out your options, you could put a span inside the link:
<span>Download Target Reports</span>
...and then hook the click event on the span, which will happen before the click on the link.
you can make javascript redirect here:-
var holder = $('.hidden-information').first();
var newOutlets = $('input[name="newoutlets"]', holder).val();
var queryDate = $('input[name="enddate"]', holder).val();
var anchor = $(this);
var link = anchor.attr('href');
link = link + "?endDate=" + queryDate + "&newOutlets=" + newOutlets;
anchor.attr('href', link);
location.href=link;
ya someone can disable js but your code is completely based on js.
Thanks
Without having a href, the click will reload the current page, so you need something like this:
jhhghj
Or prevent the scroll like this:
jhhghj
Or return false in your f1 function and:
jhhghj
....or, the unobtrusive way:
jhg
jhhghj
<script type="text/javascript">
document.getElementById("myLink").onclick = function() {
document.getElementById("abc").href="xyz.php"; `enter code here`
return false;
};
</script>

Categories

Resources