I am using https://github.com/winhtaikaung/react-tiny-link for displaying some posts from other blogs. I am able to get the previews correctly. I want to capture the views count through onClick() but this module(react-tiny-link) doesn't seems to support the same, please help.
<ReactTinyLink
cardSize="large"
showGraphic={true}
maxLine={0}
minLine={0}
header={""}
description={""}
url={url}
onClick={() => this.handleViewCount(id)} />
I tried adding div around the component but it affects the css.
You can wrap your link with a div and attach your onClick callback on that div instead.
<div onClick={() => this.handleViewCount(id)}>
<ReactTinyLink
cardSize="large"
showGraphic={true}
maxLine={0}
minLine={0}
header={""}
description={""}
url={url}
/>
</div>
Your library - ReactTinyLink does not support onClick attribute.
Since you've tagged javascript - I can give you a small JS hack for the same.
Run the following code at the end of your React Rendering
var cards = document.getElementsByClassName('react_tinylink_card');
linksClicked = [];
for(var i = 0; i<cards.length; i++){
cards[i].onclick = function(){
linksClicked.push(this.href);
}
}
The above code will go through each and every cards and will attach onClick handlers on them, once clicked - the 'this' object will be your anchor tag's element, so I am storing it's href. (you're free to store anything you want)
In the following example - https://winhtaikaung.github.io/react-tiny-link/
I tried the same snippet - and got the following result
Hope this would be a good starting point for what you're trying to achieve.
Related
I'm mapping currencies from a json file and i render the mapped currencies to a component. I have a .php file like this
<div class="currency-switch-container" id="currency_container">
<span style="font-size:12px;font-weight:bold">All currencies</span>
<div id="currency-map" style="margin-top:15px"></div>
</div>
I refer the div in the above component in my js file as follows
let currencyMap = jQuery("#currency-map");
And when my jQuery document is ready i'm doing the following
jQuery(document).ready(function($) {
$.getJSON('wp-content/themes/mundana/currency/currency.json', function(data) {
for(let c in data){
currencyMap.append(`<span onclick="onCurrencyClick(${data[c].abbreviation})"
class="currency-item">
<span>
${data[c].symbol}
</span>
<span>
${data[c].currency}
</span>
</span>`)
}
});
}
and my function is like this
function onCurrencyClick(val){
console.log("val",val);
setCookie("booking_currency", val, 14);
}
Here the function does not work. But if i do not pass anything to the function it seems to work as i can see the log in the terminal.
Hi your expression ${data[c].abbreviation} will put the value into function string without string quotes i.e. the resultant would be onCurrencyClick(abbreviation) while it should be onCurrencyClick('abbreviation').
please use onclick="onCurrencyClick('${data[c].abbreviation}')" instead.
Instead of using the inline onclick, use event delegation. This means that you have a single event listener that handles all the events from the children and grandchildren. The modification is a very minor one seeing the example here below.
A reason for doing this is that you keep your JavaScript inside your JS file. Like now, you encounter a JS error and have to look for it in your HTML. That can get very confusing. Also however inline onclick listeners are valid, they are outdated and should be avoided unless there is absolutely no other way. Compare it with using !important in CSS, same goes for that.
function onCurrencyClick(event){
var val = $(this).val();
setCookie("booking_currency", val, 14);
}
currencyMap.on('click', '.currency-item', onCurrencyClick);
This example takes the val that you try to insert from the value attribute from the clicked .current-item. <span> elements don't have such an attribute, but a <button> does and is a much more suitable element for it expects to be interacted with. It is generally a good practice to use clickable elements for purposes such as clicking.
In the example below you see the button being used and the abbreviation value being output in the value attribute of the <button> element and can be read from the onCurrencyClick function.
jQuery(document).ready(function($) {
$.getJSON('wp-content/themes/mundana/currency/currency.json', function(data) {
for(let c in data){
currencyMap.append(`
<button value="${data[c].abbreviation}" class="currency-item">
<span>
${data[c].symbol}
</span>
<span>
${data[c].currency}
</span>
</button>
`)
}
});
onclick will not work for a dynamically added div tag
Yo should follow jQuery on event
Refer: jQuery on
Stackoverflow Refer: Dynamic HTML Elements
I am currently working on a mini web application and would like some advice. I know the reason for my issue and I know one way to get around it but it would mean undoing a lot of the work that I have already done.
The issue I have is I am currently using a template string inside a for loop to print data and I have a delete button with a listener. Currently it is only working for the last button the in the list and I know it is because I am destroying the innerHTML every time I use html = x.
What I would like to know is....is there an easy way around this or should I just use append child etc instead?
for(let prod of products){
console.log("Doc ID",doc.id);
const li1 = `
<p><div>${prod.name} <div class="right"><font class=pink-text>Location:</font> $${prod.location} <button data-remove-button-id="${doc.id}" class="btn-remove">Delete</button></div></div></p>
`;
html += li1;
} //end for loop
const li2 = `
<br />
<button class="btn blue darken-2 z-depth-0 right modal-trigger" data-target="modal-prodedit">Add/Edit Attributes</button><br />
</div>
</li>
`;
html += li2;
productList.innerHTML = html;
const removeBtn = document.querySelector(`[data-remove-button-id="${doc.id}"]`);
console.log("removeBTN",removeBtn);
removeBtn.addEventListener('click', (e) => {
e.preventDefault();
console.log(`deleted row ${e.target.dataset.removeButtonId}`);
});
You are using querySelector() method which returns the first element it finds. If you want to attach that listener to all rows you need to use Document.querySelectorAll(). You'll need to differentiate between which row was selected, which doesn't seem to be in your DOM model. So I'd add a data-product-id attribute to your button, and the listener can use that to know which product was deleted.
Thanks to everyone for the help with this one.
The SelectAll worked to some extent but I decided to redo my code from scratch using DOM elements to appendChild. Once done, this made everything sooooo much easier. Decided to change it to give myself more flexibility with the code.
I have been trying to fix this problem for days without finding a solution. I am working on a web application that aims at retrieving information from a db. I am using Meteor and blaze.
As a matter of fact, i would like to change css properties in a template event wether it deals with the css proporties of the click target element or any DOM element in the same template.
Here is my template code tag :
<button type="button" class="buttonsValue" value="{{value}}">
<div class="CheckButtonsLed"></div>
</button>
Here is my template event code :
Template.devicesConfiguration.events({
'click .buttonsValue':function(e, template){
//works well on the parent of the target of the click event :
$(e.target.parentElement).css('background-color', 'chartreuse');
//works well on the target of the click event :
e.target.style.backgroundColor="#ffcccc";
//does the same thing but with a different syntax :
$(e.currentTarget).css('background-color', '#ffcccc');
// Does not work ...
var CheckButtonsLed = template.find('.CheckButtonsLed');
CheckButtonsLed.style.marginLeft = '2 em';
}
});
It seems that it does not like the margin proporties while it works for the background property. my class element is my template devicesConfiguration.
I thought first it was because the target of the margin property is not the target of my click event but i tried to change the margin of the target of the event (.buttonsvalue) without results...
does someone have an idea ? thanks a lot ! :)
Well it works now. it deals with a matter of syntax :
i wrote
simpleInput.style.padding = '2 em';
instead of ...
simpleInput.style.padding = '2em';
to put in a nutshell, to change CSS Property of a DOM element (which is not the target of the event)in a meteor template :
Template.devicesConfiguration.events({
'click .buttonsValue':function(e, template){
var simpleInput = template.find('#simpleInput');
simpleInput.style.padding = '2em';
}
});
and don't put a div element in a button tag ...
Bye !
I'm having a bit of an issue here. I had a small amount of success with event.target.templateInstance.model.thing syntax to get the value of attributes from within a repeating template but I keep getting back undefined from this bit of code I have here:
downloadFunction: function (e) {
console.log("dl function clicked");
//get particular id of thing
var fu = e.target.templateInstance.model.s.soundId;
console.log(fu);
//^ returns "TypeError: Cannot read property 'soundId' of undefined"
}
And my repeating template is here:
<div layout horizontal wrap center center-justified>
<template repeat="{{s in carddata}}">
<sound-card image="{{s.imgurl}}"
quotetext="{{s.quote}}"
soundsrc="{{s.soundurl}}"
soundref="{{s.soundId}}"
downloadfunction="{{downloadFunction}}">
</sound-card>
</template>
</div>
Where carddata is just an array with my data in it. All of the values are generated fine so I know it's not an issue with my array. I'm just confused how exactly I'm supposed to target someting from within the repeating template? Am I calling it at the wrong time? Or am I messing up the syntax of the templateInstance bit?
If it matters, I'm trying to get it to work in an Android 4.4 webView using Apache Cordova. 4.4 webView doesn't appear to enjoy the shadowDOM terribly much.
Thanks!
edit: After some jiggery pokery with console logs, it appears that the sender value is referring to the div that I apply the on-click="{{downloadFunction}} to. Here's the template that I am repeating, if this provides any insight.
<div class="soundcard-container" vertical layout>
//can't target this one either on WebView 4.4, works on ChromeOS
<img src="{{image}}" on-tap="{{playAudio}}">
<div class="soundcard-bottom-container" horizontal layout center justified>
<span>{{quotetext}}</span>
//I have an 'a' tag for desktop browsers and the div tag is targeting my Android/iOS
//apps that I am exporting as a webView to using Apache Cordova. Webonly is hidden
//at the point where I'm trying to get my downloadfunction to work.
//console.log(sender) in my downloadfunction returns this div v
<div on-tap="{{downloadfunction}}" class="mobileonly"></div>
</div>
//just a hidden audio thing for web
<div style="display: none">
<audio id="{{soundref}}" src="{{soundsrc}}" controls preload="auto"></audio>
</div>
</div>
edit2 some console logs..
console.log(sender) and console.log(event.target) are both the same div that has the on-click event for my downloadFunction.. not sure if this should be the case.
console.log(e.target.templateInstance.model) returns my <sound-card> object, I believe like it should(?)
It's just when I add the specific .s.soundId that it's undefined. I'm not sure why it's unable to find it.. Maybe there's another way to get the specific soundId (or s.soundId rather) of that particular <sound-card> object?
I'll bet you want to refer to the "sender" of the event—not e.target. See the part about inSender at https://www.polymer-project.org/0.5/docs/polymer/polymer.html#declarative-event-mapping:
inSender: A reference to the node that declared the handler. This is
often different from inEvent.target (the lowest node that received the
event) and inEvent.currentTarget (the component processing the event),
so Polymer provides it directly.
This might fix it:
downloadFunction: function (e, detail, sender) {
console.log("dl function clicked");
//get particular id of thing
var fu = sender.templateInstance.model.s.soundId;
console.log(fu);
}
Alright I was able to fit this in a different way. I wasn't able to get e.target.templateInstance.model.s.soundId bit to work, so instead on the div that I call the event on (event.target) I gave it an attribute called data-soundid and passed it {{soundref}} from my original template and then where I repeat that template I simply made a function like so:
downloady: function (e) {
console.log(e.target.getAttribute('data-soundurl'));
}
Ta da! Very nice solution. Thanks to Eyal who suggested this to me in a previous question. It works like a charm. :-)
Here is working example of using templateInstance, with included selecting by dynamic ID: Plunk .
As for your code, can't tell why it's not working.
handleEvent: function(e, detail, sender) {
console.log('handleEvent');
console.log(sender.id);
//How to catch full_obj here,
//..as if first item is clicked: full_obj = {"firstName":"John", "lastName":"Doe"}
//console.log(e);
console.log(e.target.templateInstance.model.item.firstName);
//console.log(detail);
//console.log(sender);
this.instance_firstName = e.target.templateInstance.model.item.firstName;
this.instance_lastName = e.target.templateInstance.model.item.lastName;
//Selecting by dynamic ID
var clicked_element = this.shadowRoot.querySelector('#'+this.instance_firstName);
console.log('Selecting');
console.log(clicked_element);
//var second_element = sender.templateInstance.model.querySelector('my-second-element');
//var second_element = this.$.second_element;
}
Edit:
Event handling and data binding Docs
I am working on a reflection of part of my website. This is the relevant HTML:
<div id = "original">
<img src = "picture.png" alt = "A picture" id = "picture">
<p id = "text">Some text</p>
</div>
<div id = "reflection"></div>
My Idea is copying the content of div#original to div#reflection like this:
<script>
function reflect()
{
var original = document.getElementById("original");
var reflection = document.getElementById("reflection");
reflection.innerHTML = original.innerHTML;
}
</script>
I am aware, that this will make the HTML invalid, in the whole project I iterate through the elements copied and set the IDs to not have that side effect. I just thought that this would be unnecessary to include here.
The problem I have is that the HTML I want to reflect is dynamic, so it may change. Then the reflection is wrong. I have searched for an event handler for this, but haven't found one. The only one near I found was onchange, but apparently this listens to changes in the attributes, not the child elements. Is there another one for this, or did I just use onchange wrong?
Thank you for your help!
GeF
I am aware that I could add onchange to every element, but this seemed not good style to me.
The simplest thing you can do is add a callback to reflect() every time you change the contents of the #original.
If this is not an option, you can look into a MutationObserver (documetation), as suggested here: Is there a JavaScript/jQuery DOM change listener?