how to add a (click) function inside the .ts - javascript

I am working on a solution to rewrite links in an HTML element.
I get HTML information via a JSON string 'spanClass1'. In this string I need to rewrite a class to a link. This works wonderfully. Unfortunately, I use hash routing in Angular and can only link further via the toDocument() function. It doesn't work via a normal link name tag
Via span.className.replace(/\D/g, '') I get the ID I need to link to the page.
Unfortunately I was not able to define an Angular (click) function including the ID to the page.
Also, I can't manipulate the code in the .html, only in the .ts.
document.ts
var div = document.createElement('div');
div.innerHTML = spanClass1;
div.querySelectorAll('[class^=doc-]').forEach(function (span) {
var anchor = document.createElement('a');
anchor.href = '/suche#/document/' + span.className.replace(/\D/g, '');
anchor.href = span.className.split('doc-')[1];
anchor.innerHTML = span.innerHTML;
span.parentNode.replaceChild(anchor, span);
});
spanClass1 = div.innerHTML;
toDocument(id) {
window.open('/suche#/document/' + id);
}
JSON
"spanClass1": "blablablablabla <span class=\"doc-158 \">Radleuchter,</span> blablablabla"
How do I add a (click)="toDocument(123)" function to the <a> tag inside the Component.

It seems that you want to add a event listener to a div you are creating at run time. A possible approach is to use the Renderer2 API, as provided by the Angular Team.
In this case, your code would look like the following:
In the constructor:
construct(private _renderer2: Renderer2, ...) { ... };
In the method where you create the div:
var div = document.createElement('div');
this._renderer2.listen(div, 'click', (event) => {
// Code to be run here or callback.
}
div.innerHTML = spanClass1;
...
Furthermore, I would advise some caution on changing the DOM directly. It's best to use the renderer for this since it comes with built it methods that are far safer and expose less risks.

You want to add an event listener to each a and listen for the click event. There are a few pieces of your code that I don't fully understand, but it's basically this:
function toDocument(id) {
window.open('/suche#/document/' + id);
}
var div = document.createElement('div');
div.innerHTML = spanClass1; // what is this?
div.querySelectorAll('[class^=doc-]').forEach(function (span) {
var anchor = document.createElement('a');
var id = span.className.split('doc-')[1];
anchor.href = '/suche#/document/' + span.className.replace(/\D/g, '');
anchor.innerHTML = span.innerHTML;
anchor.addEventListener('click', function() {
toDocument(id);
})
span.parentNode.replaceChild(anchor, span);
});
spanClass1 = div.innerHTML;

Related

javascript pass media EventListener to html (html5) media.currentTime

*update here is my code edit as you see working) https://codeshare.io/a3ZJ9g
i need to pass on a javascript varible to a html link...
my original question was here HTML5 video get currentTime not working with media events javscript addEventListener
working code:
<script>
var media = document.getElementById('myVideo');
// durationchange
var isdurationchange = function(e) {
$("#output").html(media.currentTime);
var x = document.createElement("a");
};
media.addEventListener("timeupdate", isdurationchange, true)
</script>
that code works
but i need it to echo the currentTime value to the html page such as
document.write("<a href=/time.htm?currentTime='.media.addEventListener("timeupdate", isdurationchange, true).'>link</a>;);
so it would print out
<a href=time.htm?currentTime=currenttimefromjavascript>link</a>
thank you
i did read:
how to pass javascript variable to html tag
How can I pass value from javascript to html?
someone suggested:
// insert the `a` somewhere appropriate so it can be clicked on:
const a = document.body.appendChild(document.createElement("a"));
a.textContent = 'Link to current time';
const isdurationchange = function(e) {
a.href = `\\time.htm?currentTime=${media.currentTime}`;
};
but where does that go?
document.write tries to write to the current document. If the document has already been processed, the document will be replaced with a blank one with your argument. You don't want that; use the proper DOM methods instead.
If, for an element you create dynamically, you want to change its href on every timeupdate, you would do:
// insert the `a` somewhere appropriate so it can be clicked on:
const a = document.body.appendChild(document.createElement("a"));
a.textContent = 'Link to current time';
const isdurationchange = function(e) {
a.href = `\\time.htm?currentTime=${media.currentTime}`;
};

I need to keep element reference to pass on

When the user clicks on <a> tag it calls a function like the following:
<a href="#" onclick="func1(this)">;
This function generates HTML for a modal that needs to reference the first button.
func1(elem) {
html='<div class="modaldiv">' +
'<a href="#" onclick="func2(e.srcElement)">'+
'</div>';
}
When the link inside the modal is clicked, func2() should save text into a data attribute inside the first link, but this is not working, returning:
"Uncaught SyntaxError: Unexpected identifier "
First, don't use inline HTML event handling attributes (onclick, onmouseover, etc.), here's why.
But, your actual problem is that you are not properly declaring your function.
This: func1(elem)
Needs to be this: function func1(elem)
Next, you <a> elements must have some content for someone to see and click on and they must then be closed, which you didn't have.
function func1(elem) {
html='<div class="modaldiv">' + 'click me too'+ '</div>';
document.body.innerHTML += html;
}
click me
If you rework your answer to use modern standards, the proper modern way to do this would be:
// Get references to DOM elements
var a1 = document.getElementById("firstAnchor");
a1.addEventListener("click", func1);
// Callback for first link:
function func1(e) {
// Store original source element
var src = e.srcElement;
// Formally create new elements and configure them
var d = document.createElement("div");
d.classList.add("modaldiv");
var a = document.createElement("a");
a.href = "#";
a.textContent = "Click me too!";
// By hooking up to a wrapper function, we can have that function
// pass arguments to the actual callback function:
a.addEventListener("click", function(){
func2(src);
});
// Add new elements to the document
d.appendChild(a);
document.body.appendChild(d);
}
function func2(firstSrc){
console.log("func2 invoked and e.srcElement from first link is: ", firstSrc);
}
click me

Don't load scripts appended with innerHTML?

I'm appending a whole HTML page to a div (to scrape). How do I stop it from requesting script, and css files ? I tried immediately removing those nodes but they still get requested.
It's for a browser addon, I'm scraping with JS
As #adeneo wrote you don't have to add the html to a page in order to scrape information from it, you can turn it into DOM tree that is disconnected from the page DOM and process it there.
In jQuery it is simple $("html text here"). Then you can scrape it using the API,
eg.
function scrape_html(html_string) {
var $dom = $(html_string);
var name = $dom.find('.name').text();
return name;
}
without jQuery:
function scrape_html(html_string) {
var container = document.createElement('div');
container.innerHTML = html_string;
var name = container.getElementsByClassName('name')[0].innerText;
return name;
}
Setting the innerHTML of a temporary HTML element that has not been added to the document, will not execute scripts, and since it does not belong to your document, the style will not be applied either.
This will give you an opportunity to strip out any unwanted elements before copying the innerHTML to your own document.
Example:
var temp = document.createElement('div');
temp.innerHTML = html; // the HTML of the 'other' page.
function removeElements(element, tagName)
{
var elements = temp.getElementsByTagName(tagName);
while(elements.length > 0)
{
elements[0].parentNode.removeChild(elements[0]);
}
}
removeElements(temp, 'script');
removeElements(temp, 'style');
removeElements(temp, 'link');
container.innerHTML = temp.innerHTML;

How to dynamically create list of <a> tags using js

I am creating html page which needs to create a list of links dynamically on a click of button. I know how to create this list when number of links to be created is known before like this:
//For 4 tags:
var mydiv = document.getElementById("myDiv");
var aTag = document.createElement('a');
aTag.innerHTML = "link1 text";
aTag.setAttribute('onclick',"func()");
mydiv.appendChild(aTag);
var bTag = document.createElement('b');
bTag.innerHTML = "link2 text";
bTag.setAttribute('onclick',"func()");
mydiv.appendChild(bTag);
var cTag = document.createElement('c');
cTag.innerHTML = "link3 text";
cTag.setAttribute('onclick',"func()");
mydiv.appendChild(cTag);
var dTag = document.createElement('d');
dTag.setAttribute('onclick',"func()");
dTag.innerHTML = "link4 text";
mydiv.appendChild(dTag);
But the problem is that the count will be known at run time and also on function call i need to identify the id of link that invoked function.. Can anybody help?
I don't know weather you receive or not the HTML to be shown in the anchor, but anyway, this should do the work:
function createAnchor(id, somethingElse) {
var anchor = document.createElement('a');
anchor.innerHTML = "link" + id + " text";
anchor.setAttribute("onclick", "func()");
return anchor;
}
Then you call the function like this:
function main(num_anchors) {
var mydiv = document.getElementById("myDiv");
for (var i = 0; i < num_anchors; i += 1) {
mydiv.appendChild(createAnchor(i));
}
}
Of course this code can be improved, but this is just for show how can this be possible.
Yes it is possible to do this at runtime .
JQuery provides very useful dom manipulation . So you can traverse the dom , filter what you need ..
you can find a lot of useful functions here .
http://api.jquery.com/category/traversing/
It would look something like this.
$( document ).ready(function() {
$( "a" ).each(function( index ) {
// enter code here..
}
});
document.ready gets invoked once the DOM has loaded.

changes not reflected in JS

I am trying to setup a new "a" component using JS function which is called , using following :
function add_div(data){
mydiv = document.getElementById("new_twt");
var link =document.createElement("a");
var text = "you have new conversations";
link.setAttribute("name",text);
link.onclick=function(){new_tweet(data);};
mydiv.appendChild(link);
}
Changes are not reflecting on the webpage , however if I use some other element such as button or new div it gets created instantly, am I missing something?
This works for me:
function add_div(data){
var mydiv = document.getElementById("new_twt");
var link = document.createElement("a");
var text = "you have new conversations";
link.name = text;
link.href = '#';
link.innerHTML = 'link';
link.onclick=function(){ new_tweet(data); return false; };
mydiv.appendChild(link);
}
I've added link text (innerHTML) so you can actually see the link
I've also added "href" so the link behaves as a link (with this you need to prevent default link action, like "return false" in the event listener, to prevent browser from jumping to the top)
Try this:
var mydiv = document.getElementById("new_twt");
var aTag = document.createElement('a');
aTag.setAttribute('href',"yourlink.htm"); //or #
aTag.innerHTML = "you have new conversations";
aTag.onclick=function(){new_tweet(data);};
mydiv.appendChild(aTag);
Here is working JS Fiddle.

Categories

Resources