Pass variable to onClick Function - javascript

Trying to open a picture in a new tab, the values comes from a looping object.
How will I pass the value of doc.strDocument to onClick ?
PUG:
a(onClick="window.open('/userImages/documents/'+doc.strDocument);")
HTML:
<a onClick="window.open('/userImages/documents/'+doc.strDocument);"></a>

Your concatenation is fine (as long as strDocument has a value that when concatenated with the static text forms a valid URL).
But, this is much simpler when it comes to <a> elements - no onclick needed because <a> elements can target new windows with the target attribute.
function getLink(){
var someData = "foo";
return "some/path/" + someData;
console.log(link.href);
}
test
And, even that should be improved by moving the JavaScript out from being inline with the HTML:
var someDynamicallyGottenValue = "foo";
var link = document.getElementById("dynamicLink");
link.href = 'http://someDomain.com/' + someDynamicallyGottenValue;
console.log(link.href);
test

You can pass JSON data to Pug.
{"book": {"name": "Dracula"}}
And your PUG code would be,
a(onClick="window.open('/userImages/documents/#{book.name}');")
Pug also support variables.
- var foo = book.name;
a(onClick="window.open('/userImages/documents/#{foo}');")
Tested using - http://naltatis.github.io/jade-syntax-docs/#variables
Hope this helps.

Related

JS sessionStorage to store HTML node and then re-use it later

I need to clone some HTML content, store it in sessionStorage, to then re-deploy the stored HTML back into the DOM on another page. For the moment with my testing I'm just doing it all on one page and summoning the sessionStorage with a page refresh.
So, here is what I have come up with so far.
var exp561CardFour = document.getElementById('dashboard_item_four');
var clnCardFour = exp561CardFour.cloneNode(true);
sessionStorage.setItem('storedCardFour', clnCardFour);
When I go to grab the HTML with this bit of code in the console...
var grabCardFour = sessionStorage.getItem('storedCardFour');
...I end up with this:
Please help :)
edit:
FYI clnCardFour just contains some HTML and it works ok
edit with Parking Masters suggestion in the console:
The Storage API (sessionStorage/localStorage) only stores strings. When you call:
sessionStorage.setItem('storedCardFour', clnCardFour);
the API uses the .toString() method against the object clnCardFour - which returns [object HTMLLIElement].
So you need the string representation of that Node. You can achieve that by getting the OuterHTML of the Node like this:
sessionStorage.setItem('storedCardFour', clnCardFour.outerHTML);
When you need to restore that Node, simply use the parent Node's .innerHTML property to place it back into the DOM.
let div = document.querySelector('div');
let exp561CardFour = document.getElementById('dashboard_item_four');
sessionStorage.setItem('storedCardFour', exp561CardFour.outerHTML);
let clonedFromStorage = sessionStorage.getItem('storedCardFour');
div.innerHTML += clonedFromStorage
<div>
<i id="dashboard_item_four">Hello there!</i>
</div>
And here is a JS Bin Example
The HTMLIElement is an <i> element, you're storing the entire element object in the storage.
You can use JSON (JavaScript Object Notation) .stringify({}) to stringify the element and then parse it again to get the element.
Here's an example of that:
var myEl = document.getElementById("my-el");
alert("This will not print the object: " + myEl);
alert("This will print the object: " + JSON.stringify(myEl));
<i id="my-el"></i>
Overflowed objects are not stringified as the object is too long.
With jQuery:
var myEl = $("my-el");
alert("This will not print the jQuery object: " + myEl);
alert("This will print the jQuery object: " + JSON.stringify(myEl));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<i id="my-el"></i>
More about JSON.stringify and JSON.parse at MDN.
(Be careful what you store in sessionStorage, you can only store up to 2kB at a time).
Now to get the parsed object using JSON.parse:
var myObj = "{}";
myObj; // "{}"
JSON.parse(myObj); // Object { ... }
I've put together a live example of everything:
var exp561CardFour = document.getElementById('dashboard_item_four');
var clnCardFour = exp561CardFour.cloneNode(true);
sessionStorage.setItem('storedCardFour', JSON.stringify(clnCardFour));
// When in an <iframe>, it'll say The operation is insecure."
var grabCardFour = JSON.parse(sessionStorage.getItem('storedCardFour'));
<i id="dashboard_item_four"><i>
The code snippet is from stacksnippets.net and will not work because of iframe security issues.
However, try it on your local server / file, and good luck.

Javascript: assign onclick inside class

I created a constructor that will handle a custom list control. I created a method in order to allow the user to add elements to the list, and I need to assign event handlers to the click events of the list elements (divs).
A simplified version of the code is here. The list elements are created using the innerHTML property and a string template upon which I substitute specific parts. Later I get the element by it's id and assign it a function in closure:
function prueba(){
var plantilla = '<div id="«id»">«texto»</div>';
var f = function(nombre){
return function(){console.log('mi nombre es ' + nombre)};
};
this.agregar = function(id, texto){
var tmp = plantilla.replace('«id»', id);
tmp = tmp.replace('«texto»', texto);
document.body.innerHTML += tmp;
document.getElementById(id).onclick = f(id);
};
};
The problem is that, apparently, the event handler is unasigned to previous created divs, so is only retained by the last one, as it can be tested with the following code:
var p = new prueba;
p.agregar('i1', 'texto1');
console.log(document.getElementById('i1').onclick.toString());//shows the function code
p.agregar('i2', 'texto2');
console.log(document.getElementById('i2').onclick.toString());//shows the function code
console.log(document.getElementById('i1').onclick.toString());//returns 'null' error
p.agregar('i3', 'texto3');
console.log(document.getElementById('i3').onclick.toString());//shows the function code
console.log(document.getElementById('i2').onclick.toString());//returns 'null' error
This happens in Iceweasel as well as in Chromium. It does NOT happen when I add 'onclick = f(«id»)' in the template (which I cannot do here because of the assigned function scope), and neither happens if I use document.createElement. What am I doing wrong?
You destroy elements previously created when you do this:
document.body.innerHTML += tmp;
Instead use insertAdjacentHMTL() if you want to append using HTML markup.
document.body.insertAdjacentHTML("beforeend", tmp);
Now instead of going through this destructive process...
serialize the existing DOM nodes to HTML
concatenate the new HTML fragment to the serialized nodes
destroy the old nodes
recreate the nodes with the new nodes
...it simply creates the new content and places it before the close of the body element.
Basically, remove element.innerHTML += ... from your coding practices. It's never necessary, it's inefficient and it causes problems like what you've described.
FYI, the .insertAdjacentHTML() method receives 4 different string possibilities as the first argument. Each one designates a position relative to the element on which you're calling it.
The strings are...
"beforebegin"
"afterbegin"
"beforeend"
"afterend"
The labels are pretty self-explanatory. They position the new content before the current element, inside the current element at the beginning, inside the current element at the end, or after the current element, respectively.
Your full code will look like this, which I shortened a bit too since the tmp really isn't needed here:
function prueba(){
var plantilla = '<div id="«id»">«texto»</div>';
var f = function(nombre){
return function(){console.log('mi nombre es ' + nombre)};
};
this.agregar = function(id, texto){
document.body.insertAdjacentHTML("beforeend",
plantilla.replace('«id»', id)
.replace('«texto»', texto));
document.getElementById(id).onclick = f(id);
};
};

how to escape single quote in dynamically created HTML tag content

In my javascript code,
I have a variable which have a string. String contains ' or quote in it. Example
var name= "hi's";
I am creating a link dynamically in a code. where it is written as a string i.e a variable content will be used dynamically to create a link on html page.
content= '<a onclick="javascript:fun(\'' + name + '\');">'
Here it is giving problem that quote in variable name completes the string in content. and hence rest portion of content is not recognised..
similar problem arises if var name = 'hi"s';
i.e. if double quote is present in it.
plz help
This is how you would create an anchor properly and completely avoid the need to escape anything.
var name = "Hi's",
anchor = document.createElement('a');
// should have an href
// links will be displayed differently by some browsers without it
anchor.href = '#';
// using onclick for pragmatic reasons
anchor.onclick = function() {
fun(name);
return false;
}
anchor.innerHTML = 'hello world';
// later
mydiv.appendChild(anchor);
Btw, the onclick attribute shouldn't start with "javascript:" at all; that's already implied.
Update
If you're still interested in the inline version, variables need two steps of encoding:
The first is to serialize the variable properly; I would use JSON.stringify() for that
The second is HTML escaping; the simplest form is simply to replace double quotes with their proper encoded values.
For example:
var content = '<a href="#" onclick="fun(' +
JSON.serialize(name).replace(/"/g, '"') + ');">hello</a>';

Getting variables values from URL after being dynamically added by JQuery

I am using this code below
var delLink = $('#deleteItem').attr('href');
to get the URL (href) of a link identified by #deleteItem.
The problem occurs when I use JQuery to add new variables onto this URL and I want to see the new dynamically added variables also displayed by the above code.
How can this be done, now it only displays the orginal URL without any of the new variables.
Thanks
delLink contains the result of your query. It is not a reference to href.
// Assigns the value of href to delLink
var delLink = $('#deleteItem').attr('href');
// Changes the href value on the DOM element
$('#deleteItem').attr('href',delLink+','+allVals);
delLink does not know about the update, to update delLink you again need to execute:
delLink = $('#deleteItem').attr('href');
What you could to make it a little easier for you is cache the jQuery object reference to the anchor element in the DOM and simply keep accessing the href attribute from it:
// Create a jQuery object reference to the anchor element in the DOM
var $delLink = $('#deleteItem');
// Changes the href value in on DOM element
var currentHref = $delLink.attr('href');
$('#deleteItem').attr('href', currentHref + ',' + allVals);
// Results are available through your reference
$delLink.attr('href');

document.getElementById as a variable in xhtml

I am trying to insert some new links using ‘innerHTML’. As there may be a number of calls on the same ‘ids’ I thought it would be wise to use variables. The following does not respond beyond the alert? The process works fine if I don’t use ‘var link’ and just enter it in full. Is there an issue perhaps trying to do this with xhtml?
Thanks.
var newlink = '<a title="new link" href="newlink.htm">New Link</a>';
var link = "document.getElementById('idlink')";
if( link ) {
alert("link confirmed");
link.innerHTML = newlink;
}
var link = "document.getElementById('idlink')";
should be
var link = document.getElementById('idlink');
You are assigning a string to the variable. Just because the contents of the string looks like code that could be run doesn't mean that it actually runs. It's just a string.
Call the method and assign the result to the variable:
var link = document.getElementById('idlink');

Categories