How to add JavaScript to Custom Elements? - javascript

I have the following code, which creates a custom element, encapsulated with Shadow DOM:
'use strict'
var proto = Object.create(HTMLElement.prototype);
proto.createdCallback = function() {
var root = this.createShadowRoot();
var divEl = document.createElement('div');
divEl.setAttribute("id", "container");
divEl.innerHTML =
"<input id='input' type='text'>"
+ "<br>"
+ "Result: <span id='result'></span>"
+ "<br><button onclick='performTask()'>Run</button>";
root.appendChild(divEl);
};
document.registerElement('custom-ele', {
prototype: proto
});
The idea is, when 'Run' is clicked, the input would be taken from the input element and processed (in performTask()), then the output placed into '#result'. My two questions are:
How would I grab the value from the input field in the Shadow DOM?
How would I place the output into #result?
This
previous stack overflow post looks like it would have answered my question, but all the suggested links are no longer valid so am wondering if anyone could point me in the right direction :)
P.S. I'd rather not use templates since HTML Imports are not being supported by all browsers and I want all of my custom element code contained in one file.

Turns out you can add functions to the shadow root itself, then you can just call this.parentNode.fn() on the shadow roots direct children to access the shadowRoot...
proto.createdCallback = function() {
let root = this.createShadowRoot();
root.innerHTML = "<input id='input' type='text'>"
+ "<br>"
+ "Result: <span id='result'></span>"
+ "<br><button onclick='this.parentNode.process()'>Run</button>";
this.shadowRoot.process = function() {
let spanEle = this.querySelector('span');
let inputEle = this.querySelector('input');
spanEle.textContent = performAlgorithm(inputEle.value.split(','));
};
};
document.registerElement('custom-ele', { prototype: proto });
(Thanks to MarcG for giving me the initial insight)

WITH CLOSURE
You can use the method querySelector on your Shadow DOM root to get inside elements:
'use strict'
var proto = Object.create( HTMLElement.prototype )
proto.createdCallback = function ()
{
//HTML ROOT
var root = this.createShadowRoot()
root.innerHTML = "<input id='input' type='text'>"
+ "<br>"
+ "Result: <span id='result'></span>"
+ "<br><button>Run</button>"
//UI
var buttonEle = root.querySelector( "button" )
var inputEle = root.querySelector( "input" )
var spanEle = root.querySelector( "#result" )
buttonEle.onclick = function ()
{
var input = inputEle.value
// do some processing...
spanEle.textContent = input
}
}
document.registerElement( 'custom-ele', { prototype: proto } )
NB: you can use template without HTML Imports, in the same page. See the following snippet:
<html>
<body>
<custom-ele></custom-ele>
<template id="custelem">
<input id='input' type='text'>
<br>Result:
<span id='result'></span>
<br>
<button>Run</button>
</template>
<script>
var proto = Object.create(HTMLElement.prototype)
proto.createdCallback = function() {
//HTML ROOT
var root = this.createShadowRoot()
root.innerHTML = custelem.innerHTML
//UI
var buttonEle = root.querySelector("button")
var inputEle = root.querySelector("input")
var spanEle = root.querySelector("#result")
buttonEle.onclick = function() {
var input = inputEle.value
// do some processing...
spanEle.textContent = input
}
}
document.registerElement('custom-ele', {
prototype: proto
})
</script>
</body>
</html>
WITHOUT CLOSURE
If you don't want to use closure, you can declare a method called handleEvent on your custom element, and add an Event Listener that will redirect on it:
proto.createdCallback = function ()
{
//HTML ROOT
var root = this.createShadowRoot()
root.innerHTML = custelem.innerHTML
//EVENT
var buttonEle = root.querySelector( "button" )
buttonEle.addEventListener( "click", this )
}
proto.handleEvent = function ( ev )
{
var inputEle = this.shadowRoot.querySelector( "input" )
var spanEle = this.shadowRoot.querySelector( "#result" )
// do some processing...
spanEle.textContent = inputEle.value
}

Related

Update properties in POPUP , with leaflet and geoJson

I've made a script based on : update properties of geojson to use it with leaflet
>>>Working script picture
But I have an issue with multiple arguments.. I'd like to put 2 separate variables like:
layer.feature.properties.desc = content.value;
layer.feature.properties.number = content2.value;
But
layer.bindPopup(content).openPopup()
can open only one - "content", there is an error when I put for example:
layer.bindPopup(content + content2).openPopup();
>>> Picture
So I made another script:
function addPopup(layer)
{let popupContent =
'<form>' +
'Description:<br><input type="text" id="input_desc"><br>' +
'Name:<br><input type="text" id="input_cena"><br>' +
'</form>';
layer.bindPopup(popupContent).openPopup();
document.addEventListener("keyup", function() {
link = document.getElementById("input_desc").value;
cena = document.getElementById("input_cena").value;
layer.feature.properties.link = link;
layer.feature.properties.cena = cena;
});
};
>>>Picture
But unfortunately:
layer.feature.properties.link = link;
layer.feature.properties.cena = cena;
Is the same for each drawn geometry. Moreover when user fill the form, the arguments will dissaper just after close PopUp.. With update properties of geojson to use it with leaflet script inscribed argument is visible each time when user "click" on PupUp
Can any one help me on this?
You have to add the listener in the popupopen event.
Change your addPopup function to:
var openLayer;
function addPopup(layer){
let popupContent =
'<form>' +
'Description:<br><input type="text" id="input_desc"><br>' +
'Name:<br><input type="text" id="input_cena"><br>' +
'</form>';
layer.bindPopup(popupContent).openPopup();
layer.on("popupopen", function (e) {
var _layer = e.popup._source;
if(!_layer.feature){
_layer.feature = {
properties: {}
};
}
document.getElementById("input_desc").value = _layer.feature.properties.link || "";
document.getElementById("input_cena").value = _layer.feature.properties.cena || "";
document.getElementById("input_desc").focus();
openLayer = _layer;
});
layer.on("popupclose", function (e) {
openLayer = undefined;
})
};
L.DomEvent.on(document,"keyup",function(){
if(openLayer){
link = document.getElementById("input_desc").value;
cena = document.getElementById("input_cena").value;
openLayer.feature.properties.link = link;
openLayer.feature.properties.cena = cena;
}
})
https://jsfiddle.net/falkedesign/ntvzx7cs/

get innerHTML of the children of the currentTarget

I have this part of my html (more than one of same type):
<div class="this-product">
<img src="images/bag2.jpeg" alt="">
<span class="product-name">iPhone</span>
<span class="product-price">345445</span>
</div>
And this part of my javascript code meant to get the innerHTML of the span tags and assign them values as shown:
var productList = document.querySelectorAll('.this-product');
productList.forEach(function (element) {
element.addEventListener('click', function (event) {
var productName = document.getElementsByClassName('product-name')[0].innerHTML;
var productPrice = document.getElementsByClassName('product-price')[0].innerHTML;
var cartProductname = event.currentTarget.productName;
var cartProductprice = event.currentTarget.productPrice;
var cartContent = '<div class="cart-product"><span class="block">'+cartProductname+'</span><span class="block">'+cartProductprice+'</span></div><div class="cart-result">Total = </div><br>'
document.getElementById('dashboard-cart').innerHTML += cartContent;
});
});
Everything works well and every variable above has its value shown well apart from cartProductname and cartProductprice which display as undefined and also vscode tells me that productName is declared but not read. Where could I be wrong?
If I understand your question correctly, you could call querySelector on each product item element that you are iterating like so:
var productList = document.querySelectorAll('.this-product');
productList.forEach(function (element) {
element.addEventListener('click', function (event) {
// Update these two lines like so:
var productName = element.querySelector('.product-name').innerHTML;
var productPrice = element.querySelector('.product-price').innerHTML;
var cartProductname = productName; // event.currentTarget.productName;
var cartProductprice = productPrice; // event.currentTarget.productPrice;
var cartContent = '<div class="cart-product"><span class="block">'+cartProductname+'</span><span class="block">'+cartProductprice+'</span></div><div class="cart-result">Total = </div><br>'
document.getElementById('dashboard-cart').innerHTML += cartContent;
});
});
You can use event.currentTarget.querySelector('.product-name') to get element inside of another element

JQuery using object literal can't using $(this) always undefine on onclick

my problem after write as object literal as Jquery guide i can't using $(this) to access self on onlick="". please help correct my mistake.
my html
<a
data-id="<?=$product_id?>"
class="compare product-<?=$product_id?>"
onclick="(function(){compareInit.comGet();})()"
></a>
my js
var compareInit = {
/* Store Item Compare */
comGet: function() {
var e = $(this);
var item_id = e.data('id');
var item_image = e.find(".compare-hidden-image").val();
var item_name = e.find(".compare-hidden-name").val();
var count_item = $(".compare-item").length;
var item_dialog = $(".compare-tray-dialog");
var compare_button = $(".compare-tray-item");
item_dialog.show();
if (count_item > 1) {
} else {
$(".product-"+ item_id).css("color", "red").attr('onclick','');
}
if (count_item === 0) {
compare_button.removeClass('activate').addClass('deactivate');
} else {
compare_button.removeClass('deactivate').addClass('activate');
}
$('.compare-remove').on("click", function() {
var rem_id = $(this).data('id');
$("." + rem_id).remove();
$(".product-" + rem_id).css("color", "#fff").attr('onclick','(function(){compareInit.comGet();})()');
compare_button.removeClass('activate').addClass('deactivate');
});
}
};
Thank in advance.
You can pass the this identifier from the onclick event and then access it under a name other than this such as elem as a parameter of your function.
var compareInit = {
/* Store Item Compare */
comGet: function(elem) {
console.log("working");
var e = $(elem);
var item_id = e.data('id');
var item_image = e.find(".compare-hidden-image").val();
var item_name = e.find(".compare-hidden-name").val();
var count_item = $(".compare-item").length;
var item_dialog = $(".compare-tray-dialog");
var compare_button = $(".compare-tray-item");
item_dialog.show();
if (count_item > 1) {} else {
$(".product-" + item_id).css("color", "red").attr('onclick', '');
}
if (count_item === 0) {
compare_button.removeClass('activate').addClass('deactivate');
} else {
compare_button.removeClass('deactivate').addClass('activate');
}
$('.compare-remove').on("click", function() {
var rem_id = $(this).data('id');
$("." + rem_id).remove();
$(".product-" + rem_id).css("color", "#fff").attr('onclick', '(function(){compareInit.comGet();})()');
compare_button.removeClass('activate').addClass('deactivate');
});
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a data-id="3636" class="compare product-3636" onclick="compareInit.comGet(this)">Testing</a>
You need to pass-on the your required DOM element's this reference as follows:
onclick="(function(){compareInit.comGet();})()"; here you are invoking an anonymous function without passing anything to it. So there inside it this reference means that anonymous function itself. To achieve your goal you need to pass DOM reference as follows:
var compareInit = {
/* Store Item Compare */
comGet: function(thisRef) {
alert($(thisRef).text());
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="mydiv" onclick="(function(thisRef){compareInit.comGet(thisRef);})(this)">Click Me!</div>
Try this: apply the this inside the onclick function .If you apply this in object function its get the data from that object only
var compareInit ={
comGet : function(that){
console.log(that.innerHTML)
}
}
<a onclick="compareInit.comGet(this)">hello</a>
Alternate:
If get the this from whole object try with return like below .its like a jquery object $(element).html()
var compareInit = function(that){
return {
comGet : function(){
console.log(that.innerHTML)
}
}
}
<a onclick="compareInit(this).comGet()">hello</a>

adding and delete script doesn't work with removeChild()

I'm having some trouble with my code. the only thing i have to make is an add and delete button. The adding part is already done, but the delete part not. it keeps saying:
uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'
Can someone please help me?
Thanks!
Code:
<input type="text" id="txtelement">
<button id="add">result</button>
<button id="delete">Delete latest</button>
<p id="divResult"></p>
<script>
//decline variable
var index = 1;
//adding option
window.onload = function(){
document.getElementById('add').onclick = function(){
var newElement = document.createElement('div');
varElementid = 'div' + index++;
var node = document.getElementById('txtelement').value;
var newNode = document.createTextNode(node);
newElement.appendChild(newNode);
console.log(newElement);
document.getElementById('divResult').appendChild(newElement);
}
//delete option
document.getElementById('delete').onclick = function(){
var divResult = document.getElementById('divResult');
var alinea = divResult.querySelectorAll('p:last-child')[0];
console.log(alinea + ' word verwijderd...');
divResult.removeChild(alinea);
console.log('verwijderd!');
}
}
:last-child works slightly different than you think it does. p:last-child selects the last child of type p(aragraph) of [whatever parent node you called the method on]'. You don't want to select the p, you want to select the div you just inserted.
var alinea = divResult.querySelectorAll('div:last-child')[0]
Do note that your code doesn't handle the case yet where you delete more elements than you added.
Running code snippet:
//decline variable
var index = 1;
//adding option
window.onload = function() {
document.getElementById('add').onclick = function() {
var newElement = document.createElement('div');
varElementid = 'div' + index++;
var node = document.getElementById('txtelement').value;
var newNode = document.createTextNode(node);
newElement.appendChild(newNode);
console.log(newElement);
document.getElementById('divResult').appendChild(newElement);
}
//delete option
document.getElementById('delete').onclick = function() {
var divResult = document.getElementById('divResult');
var alinea = divResult.querySelectorAll('div:last-child')[0];
console.log(alinea + ' word verwijderd...');
divResult.removeChild(alinea);
console.log('verwijderd!');
}
}
<input type="text" id="txtelement">
<button id="add">result</button>
<button id="delete">Delete latest</button>
<p id="divResult"></p>

How could I call a JQuery function upon a button click?

I have a JQuery function that fetches and displays a page worth of images through the use of JSON files. I want to display the next set of images upon a button click, but that requires adding on a short string to the request url, which is found and stored in a var when I first run the script. I need to call this JQuery function again and pass the string var to it (lastId in code below). I am an utter noob with JavaScript in general and don't know how to go about doing that.
Here is a full version of the code:
$(function runthis(un){
var lastId;
un = typeof un !== 'undefined' ? un : "";
$('#domainform').on('submit', function(event){
event.preventDefault();
$('#content').html('<center><img src="img/loader.gif" alt="loading..."></center>');
//var lastId;
var domain = $('#s').val();
var newdomain = domain.replace(/\//g, ''); // remove all slashes
var requrl = "http://www.reddit.com/r/";
var getmore;
getmore = "?after=t3_"+un;
var fullurlll = requrl + domain + ".json" + getmore;
$.getJSON(fullurlll, function(json){
var listing = json.data.children;
var html = '<ul class="linklist">\n';
for(var i=0, l=listing.length; i<20; i++) {
var obj = listing[i].data;
var votes = obj.score;
var title = obj.title;
var subtime = obj.created_utc;
var thumb = obj.thumbnail;
var subrdt = "/r/"+obj.subreddit;
var redditurl = "http://www.reddit.com"+obj.permalink;
var subrdturl = "http://www.reddit.com/r/"+obj.subreddit+"/";
var exturl = obj.url;
var imgr = exturl;
var imgrlnk = imgr.replace("target=%22_blank%22","");
var length = 14;
var myString = imgrlnk;
var mycon = imgrlnk;
var end = mycon.substring(0,14);
myString.slice(-4);
var test1 = myString.charAt(0);
var test2 = myString.charAt(1);
var timeago = timeSince(subtime);
if(obj.thumbnail === 'default' || obj.thumbnail === 'nsfw' || obj.thumbnail === '')
thumb = 'img/default-thumb.png';
if(end == "http://i.imgur" ){
$("#MyEdit").html(exturl);
html += '<li class="clearfix">\n';
html += '<img src="'+imgrlnk+'" style="max-width:100%; max-height:750px;">\n';
html += '</li>\n';
html += '<div class="linkdetails"><h2>'+title+'</h2>\n';
/*html += '<p class="subrdt">posted to '+subrdt+' '+timeago+'</p>'; /*'+test1+test2+'*/
html += '</div></li>\n';
}
if (listing && listing.length > 0) {
lastId = listing[listing.length - 1].data.id;
} else {
lastId = undefined;
}
} // end for{} loop
htmlOutput(html);
}); // end getJSON()
}); // end .on(submit) listener
function htmlOutput(html) {
html += '</ul>';
$('#content').html(html);
}
});
The way you currently are executing the function run this doesn't ever leave you a handle to that function. This means it only really exists in the context of document.ready (what $(function()) is a shortcut for).
What you want to do instead is to keep a reference to this function for later use.
If you want to be able to put it directly into an onclick='' you will need to put the function in global,
eg:
var myFunction = function() { /*Stuff here*/}
$(myFunction)
this declares a function called myFunction and then tells jQuery to execute it on document ready
Global is generally considered pretty naughty to edit. One slightly better option would be to assign the click to the button inside your javascript
eg:
$(function(){
var myFunction = function() { /*Stuff here*/}
myFunction(); //call it here
$('#my-button-id').click(myFunction);//attach a click event to the button
)
This means that the function myFunction only exists in the scope of your document.ready, not in global scope (and you don't need onclick='' at all)
tTo add listener on some event you can use live('click',function(){}) Like yhis:
<div id="my-button">some content</div>
<script type="text/javascript">
$('#my-button').live('click',function(){
//your code
})
</script>

Categories