changes not reflected in JS - javascript

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.

Related

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

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;

jQuery selector troubles - trying to select and log links

I'm making a Chrome extension that acts on Facebook's newsfeed. I'm trying to select the URL starting with "https://external-ort2-2.xx" from Facebook's "_q7o" div and log it to the console (function capturePic). The earlier code, which inserts a button after the "_q7o" div, works fine, so I think I'm selecting the right div. But URL isn't getting logged.
Many thanks!
function callAttentionToX(jNode) {
var uCW = jNode.closest("div._q7o");
var button = document.createElement("a");
button.innerHTML = "I'm a button";
button.style.float= "left";
uCW.append(button);
}
function capturePic(jNode) {
var uCW = jNode.closest("div._q7o");
var firstHref = $(".uCW a[href^='https://external-ort2-2.xx']").attr("href");
console.log(firstHref);
}
waitForKeyElements("[aria-label$='Story options']", callAttentionToX, capturePic);

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.

Jquerymobile create button using javascript

i am trying to create href using javascript which should have data-role="button". But the button is not showing. Here is my code.
var a = document.createElement("A");
a.appendChild(document.createTextNode("Skúsiť Znova"));
a.setAttribute("onClick","checkConnection();");
a.setAttribute("data-role","button");
a.setAttribute("data-inline","true");
a.setAttribute("data-corner","false");
I append this to div as child and I can see text and also onClick parameter is working great. But for some reason it isnt showing as button but as normaln href. Any suggestions on how to create jquerymobile button dynamicaly with JS? This is whole code:
$(document).ready(function(){
var a = document.createElement("A");
var div = document.createElement("div");
var span = document.createElement("span");
var p2 = document.createElement("p");
var p = document.createElement("p");
a.appendChild(document.createTextNode("Skúsiť Znova"));
a.setAttribute("onClick","checkConnection();");
a.setAttribute("data-role","button");
a.setAttribute("data-inline","true");
a.setAttribute("data-corner","false");
div.setAttribute("id","alertMessage");
span.appendChild(document.createTextNode("Pripojenie zlyhalo"));
p2.setAttribute("style","text-align: center;");
span.setAttribute("class","red");
p.appendChild(span);
p.appendChild(document.createTextNode(" (skontrolujte nastavenia siete)."));
div.appendChild(p);
p2.appendChild(a);
div.appendChild(p2);
var mainDiv = document.getElementById("alert");
mainDiv.appendChild(div);
$('mainDiv').trigger('create');
var toppos=($(window).height()/2) - ($("#alertMessage").height()/2);
var leftpos=($(window).width()/2) - ($("#alertMessage").width()/2);
$("#alertMessage").css("top", toppos).css("left",leftpos);
});
You can use trigger('create') to apply all of the jQuery Mobile formatting. Full working code:
HTML:
<div id="container"></div>
JavaScript:
var a = document.createElement("A");
a.appendChild(document.createTextNode("Skúsiť Znova"));
a.setAttribute("onClick","checkConnection();");
a.setAttribute("data-role","button");
a.setAttribute("data-inline","true");
a.setAttribute("data-corner","false");
$('#container').append(a).trigger('create');
This can be seen in action here: http://jsfiddle.net/sQ2dA/.
In response to your edits: the issue is that you have mainDiv in quotes, so you are passing a string on this line:
$('mainDiv').trigger('create');
But you should be passing the variable mainDiv:
$(mainDiv).trigger('create');
Please see the working example here: http://jsfiddle.net/P62Cp/.
var a = document.createElement("button");
a.innerText = "Submit";
a.id = "addition";
document.body.appendChild(a);

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