how to show up an hyperlink into html from json - javascript

I have this json:
tipo={
"type":"FeatureCollection",
"crs":{
"type":"name",
"properties":{
"name":"urn:ogc:def:crs:OGC:1.3:CRS84"
}
},
"features":[
{
"type":"Feature",
"properties":{
"pic":"./p2.png",
"nombre":"T2V",
"web":"www.t2v.com"
},
"geometry":{
"type":"Point",
"coordinates":[
-4.45497,
36.692029
]
}
},
{
"type":"Feature",
"properties":{
"pic":"./p2.png",
"nombre":"NETBLUE",
"web":"www.netblue.es"
},
"geometry":{
"type":"Point",
"coordinates":[
-4.427596,
36.713663
]
}
},
]
}
I need to show up the hyperlink of each fields in a popup in html with this code:
`
var info = L.control();
info.onAdd = function (map) {
this._div = L.DomUtil.create('div', 'info');
this.update();
return this._div;
};
info.update = function (props) {
// console.log(props);
this._div.innerHTML = ''
+(props? '<br><img src="'+props.pic+'"style="height:75px; display: block;margin-left: auto;margin-right: auto;">': '')
+(props? '<b><center style="color:#838383; margin-top:10px;">'+props.nombre+'</center></b>': '')
+(props? '<br><b><center style="color:#838383"><a href>'+props.web+'</a></center></b>': '');
this._div.innerHTML += '<br /><img src="link.png" style="background:#FFC627; margin-left:20px; margin-right:15px; margin-top:0px">';
};
info.addTo(map);`
But the problem is that the hyperlink shows up in the popup with the tipical underlines but when i click in the hyperlink, the webpage only refresh, it doesn't go to the respective webpage of the json.

'<a href>'+props.web+'</a>' isn't how the links are supposed to work (in fact, it's invalid HTML)
The href attribute should contain as value the address of the link.
'I am a working link'
Please take a look at the documentation for more informations about the <a></a> tag.
My last sentence could be written in HTML such way
<p>
Please take a look at the documentation for more informations about the <code><a></a></code> tag.
</p>

Related

Context Menu array?

I have written a simple extension for a company website that reads the array of projects, and alerts the title of the project when I hover over it. This works perfectly, but it is not what I'm looking for:
let projects = document.getElementsByClassName("project-name");
extract_data = function() {
let title = this.getElementsByClassName("project-name ng-binding")[0].getAttribute("title")
alert(title);
};
for (var i = 0; i < projects.length; i++) {
projects[i].addEventListener('mouseover', extract_data, false);
}
I would like to slightly modify my code so that instead of alerting on mouseover, the alert is added as an option to the Chrome Context Menus. Something similar to:
chrome.contextMenus.create({
title: "Alert Project Title",
contexts:["selection"], // ContextType
onclick: extract_data // A callback function
});
This is not quite right because I need to change the context menu to be dependent on the project row, and as this is written now, there is no reference to projects for the Context Menu.
Is there any easy way to change my mouseover to become the value of the contextMenu?
Perhaps I was too hasty.
If you want that the menù displays an items with the TITLE of selected project (not selected text)
and if you want to move ALERT as single contextMenu item onclick event
I think you HAVE A CHANCE!
But you have to inject a content script declaratively
/* in manifest.json */
...
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["cs.js"],
"run_at": "document_idle"
}]
...
/* in content script "cs.js" */
function extract_data() {
var title = this.getElementsByClassName("project-name ng-binding")[0].getAttribute("title");
chrome.runtime.sendMessage({'title': title}, resp =>
console.log('backgroung script has received the message and send back this message: ' + resp.msg)
)
}
var projects = document.getElementsByClassName("project-name");
for (var i = 0; i < projects.length; i++)
projects[i].addEventListener('mouseover', extract_data, false)
/* in background script */
function createMenu() {
chrome.contextMenus.create({
'id': '1',
'title': 'Alert Project Title',
'contexts': ["selection"],
'documentUrlPatterns': ["<all_urls>"],
'enabled': false
}, _ => {
if (chrome.runtime.lastError) {} else {}
})
}
function handleInstalled(details) {
createMenu()
}
chrome.runtime.onInstalled.addListener(handleInstalled);
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
chrome.contextMenus.update(
'1',
{
"title": "Do you want to alert " + msg.title + " project title",
'contexts': ["selection"],
'documentUrlPatterns': ["<all_urls>"],
"enabled": true,
"onclick": _ => alert(msg.title)
},
_ => {
sendResponse( {'msg': chrome.runtime.lastError ? 'Some error...' : 'Fine!' } )
}
)
return true
})
If you want that the menù displays an items with the title of selected project I think you are out of luck. I don't believe there is a way to do it.
But If you want the menù displays an items with your selection try this.
chrome.contextMenus.create({
"id": "1",
title: "Do you want to alert '%s' project title",
"contexts": ["selection"],
"documentUrlPatterns": [...],
onclick: extract_data // A callback function
})

chrome.contextmenus how to get html instead of string

I'm new on chrome extension,
I'm creating a basic extension, thats will show the selected html with tags (spans, divs and all other DOMs) on an alert
I try this chrome.contextMenus.create (code below) but it showing just the selected string
chrome.contextMenus.create({title: "Selected HTML", contexts:["selection"], onclick: showSelectedHtml});
I just want to know if theres a way to get selected html doms(with tags if available) instead of string!
Thanks;
As you can see in the documentation contextMenus API can't do that.
The solution is to run a content script that gets the HTML and returns it into your background script.
manifest.json:
"permissions": ["activeTab", "contextMenus"],
"background": {
"scripts": ["background.js"],
"persistent": false
}
background.js:
// in Chrome the menus should be created only at install/update
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: 'sel',
title: 'Selected HTML',
contexts: ['selection'],
}, () => chrome.runtime.lastError); // ignore errors about an existing id
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
chrome.tabs.executeScript(tab.id, {
code: `(${getSelectedHtml})()`,
frameId: info.frameId,
matchAboutBlank: true,
runAt: 'document_start',
}, data => {
if (chrome.runtime.lastError) {
alert('Error: ' + chrome.runtime.lastError.message);
} else {
prompt('HTML', data[0]);
}
});
});
// this function's code will be executed as a content script in the web page
function getSelectedHtml() {
const sel = getSelection();
let html;
if (sel.rangeCount) {
const div = document.createElement('div');
div.appendChild(sel.getRangeAt(0).cloneContents());
html = div.innerHTML;
}
return html || '';
}
Note: don't use the onclick property in contextMenus.create() because it doesn't work with "persistent":false background script, which is the preferred type (more info).

Use dynamically created link to download file in AngularJS

I'm using ng-click to call a function which makes a post http request to the server and then creates a link. How can I use this created link to also download the file attached to it?
My template
<button ng-click="getFile(row)">Download</button>
My controller
$scope.getFile = function(row){
row.isSelected = true;
var link = null;
var postData = {
"data" : {
"type": "member_report",
"relationships": {
"member" : {
"data": {
"type": "user",
"id": memberID
}
}
}
}
}
ajaxRequest.ajaxPost('http://someApi.com', postData).then(
function(jsonAPI) {
link = jsonAPI.links.download; //here is the response link
//todo something with it to download file
},
function(errorResponse) {
}
);
}
By the way ajaxRequest is just a simple $http service wrapper.
If I understood you, then I suppose that you want to initiate the download as soon as you get the link dynamically, then you can proceed as follows
$scope.getFile = function(row){
row.isSelected = true;
var link = null;
var postData = {
"data" : {
"type": "member_report",
"relationships": {
"member" : {
"data": {
"type": "user",
"id": memberID
}
}
}
}
}
ajaxRequest.ajaxPost('http://someApi.com', postData).then(
function(jsonAPI) {
link = jsonAPI.links.download;
// Now we want to download the link
var downloadLink = document.createElement('a');
downloadLink .href = link;
// now set the visibility to hidden so that it doesnt effect the frontend layout
downloadLink .style = 'visibility:hidden';
downloadLink .download = 'file_name';
// now append it to the document, generate click and remove the link
document.body.appendChild(downloadLink );
downloadLink .click();
document.body.removeChild(downloadLink );
},
function(errorResponse) {
}
);
}
Try to save the link in the the $scope. Then, use this:
<a target="_self" href={{your variable}} download="foo.pdf">
Also check the documentation:
http://docs.angularjs.org/guide/
Answer taken from here:
How do you serve a file for download with AngularJS or Javascript?
I managed to do it using the $window service.
ajaxRequest.ajaxPost('http://someApi.com', postData).then(
function(jsonAPI) {
link = jsonAPI.links.download;
$window.location.href = link;
},
function(errorResponse) {
}
);
Just had to add $window as a dependency

How can I make magnific-popup open an selected item in a inline gallery?

I am using magnific-popup to display an inline gallery (with custom HTML markup), precisely like the example here. This opens a gallery of custom markup, where you can click through 3 sets of avatar/name/location data. (Try the example or the code below and you'll see what I mean).
However, I can't find a way to open the second (or anything besides the first) element on an anchor click.
Has anyone used magnific-popup and and been able to open an inline element other than the first element?
HTML:
<button style="padding:20px;">Open popup</button>
CSS:
.white-popup {
position: relative;
background: #FFF;
padding: 20px;
width: auto;
max-width: 200px;
margin: 20px auto;
text-align: center;
}
Javascript:
// Define data for the popup
var data = [
{
username: "Brad Frost", // Key "username" means that Magnific Popup will look for an element with class "mfp-username" in markup and will replace its inner HTML with the value.
userWebsite_href: 'http://www.bradfrostweb.com', // Key "userWebsite_href" means that Magnific Popup will look for an element with class "mfp-userWebsite" and will change its "href" attribute. Instead of ending "href" you may put any other attribute.
userAvatarUrl_img: 'https://si0.twimg.com/profile_images/1561258552/brad_frost_bigger.png', // Prefix "_img" is special. With it Magnific Popup finds an element "userAvatarUrl" and replaces it completely with image tag.
userLocation: 'Pittsburgh, PA'
},
{
username: "Paul Irish",
userWebsite_href: 'http://paulirish.com',
userAvatarUrl_img: 'https://si0.twimg.com/profile_images/2910976341/7d972c32f3882f715ff84a67685e6acf_bigger.jpeg',
userLocation: 'San Francisco'
},
{
username: "Chris Coyier",
userWebsite_href: 'http://css-tricks.com',
userAvatarUrl_img: 'https://si0.twimg.com/profile_images/1668225011/Gravatar2_bigger.png',
userLocation: 'Palo Alto, California'
}
];
// initalize popup
$('button').magnificPopup({
key: 'my-popup',
items: data,
type: 'inline',
inline: {
// Define markup. Class names should match key names.
markup: '<div class="white-popup"><div class="mfp-close"></div>'+
'<a class="mfp-userWebsite">'+
'<div class="mfp-userAvatarUrl"></div>'+
'<h2 class="mfp-username"></h2>'+
'</a>'+
'<div class="mfp-userLocation"></div>'+
'</div>'
},
gallery: {
enabled: true
},
callbacks: {
markupParse: function(template, values, item) {
// optionally apply your own logic - modify "template" element based on data in "values"
// console.log('Parsing:', template, values, item);
}
}
});
Add this to your magnificPopup function and this will open up the second item on click:
index:2,
Listed on the documentation here.
Example Codepen
Check out this Codepen:
http://codepen.io/mgo/pen/ykgjb
Or try my way of solving the problem: https://codepen.io/jnax/pen/RpyVxx
var clickedButton;
$('button').click(function(){
clickedButton = $('button').index(this);
}); //this indexing solution is obviously not the best for all situations
then, when the popup opens, goTo the corresponding index in the popup.
callbacks: {
open: function(){$('button').magnificPopup('goTo',clickedButton)}}
The problem with this is, the goTo action is visible although I suppose it could be masked by a css transition
Slight variation on the above worked for me
// Define data for the popup
var data = [
{
username: "Brad Frost", // Key "username" means that Magnific Popup will look for an element with class "mfp-username" in markup and will replace its inner HTML with the value.
userWebsite_href: 'http://www.bradfrostweb.com', // Key "userWebsite_href" means that Magnific Popup will look for an element with class "mfp-userWebsite" and will change its "href" attribute. Instead of ending "href" you may put any other attribute.
userAvatarUrl_img: 'https://si0.twimg.com/profile_images/1561258552/brad_frost_bigger.png', // Prefix "_img" is special. With it Magnific Popup finds an element "userAvatarUrl" and replaces it completely with image tag.
userLocation: 'Pittsburgh, PA'
},
{
username: "Paul Irish",
userWebsite_href: 'http://paulirish.com',
userAvatarUrl_img: 'https://si0.twimg.com/profile_images/2910976341/7d972c32f3882f715ff84a67685e6acf_bigger.jpeg',
userLocation: 'San Francisco'
},
{
username: "Chris Coyier",
userWebsite_href: 'https://css-tricks.com',
userAvatarUrl_img: 'https://si0.twimg.com/profile_images/1668225011/Gravatar2_bigger.png',
userLocation: 'Palo Alto, California'
}
];
// initalize popup
$('button').click(function(){
let index = $('button').index(this);
console.log("button index",index)
$(this).magnificPopup({
key: 'my-popup',
items: data,
type: 'inline',
index:index,
inline: {
// Define markup. Class names should match key names.
markup: '<div class="white-popup"><div class="mfp-close"></div>'+
'<a class="mfp-userWebsite">'+
'<div class="mfp-userAvatarUrl"></div>'+
'<h2 class="mfp-username"></h2>'+
'</a>'+
'<div class="mfp-userLocation"></div>'+
'</div>'
},
gallery: {
enabled: true
},
callbacks: {
markupParse: function(template, values, item) {
// optionally apply your own logic - modify "template" element based on data in "values"
// console.log('Parsing:', template, values, item);
},
open: function() {
// Will fire when this exact popup is opened
// this - is Magnific Popup object
console.log("inside open",index)
},
}
});
});

Change Jquery animimation dynamically

I am trying to change kernburns slideshow after the page loading, for example after pressing a button.
This is the code of http://jsfiddle.net/s4C5K/1/
HTML CODE:
<div id="kenburns-slideshow"></div>
<div id="kenburns-description">
<h1 id="status">Loading Images..</h1>
<h1 id="slide-title"></h1>
<h1 class="title"><a href="http://www.github.com/toymakerlabs/kenburns/" target="blank">Kenburns.js
</a></h1>
<p>Kenburns.js is a lightweight and flexible Jquery gallery plugin that loads images and features an animated, pan-and-zoom, Ken Burns style effect. Grab the source from my Github</p>
</div>
<button onclick="slidechange()">New slide</button>
JS CODE:
the code simply initiate the slideshow. The function slidechange() empties the div and change the "images" variable and redo the operations:
var titles = ["Epic Day at Refugio",
"Colors of Spring",
"First Flowers",
"Magic Hour at Sands Beach",
"Coal Oil Point",
"Hope Ranch Views"];
$(document).ready(function() {
$('#kenburns-slideshow').Kenburns({
images: [
"http://www.toymakerlabs.com/kenburns/images/image0.jpg",
"http://www.toymakerlabs.com/kenburns/images/image1.jpg",
"http://www.toymakerlabs.com/kenburns/images/image2.jpg",
"http://www.toymakerlabs.com/kenburns/images/image3.jpg",
"http://www.toymakerlabs.com/kenburns/images/image4.jpg",
"http://www.toymakerlabs.com/kenburns/images/image5.jpg" ],
scale:0.75,
duration:8000,
fadeSpeed:1200,
ease3d:'cubic-bezier(0.445, 0.050, 0.550, 0.950)',
onSlideComplete: function(){
$('#slide-title').html(titles[this.getSlideIndex()]);
},
onLoadingComplete: function(){
$('#status').html("Loading Complete");
}
});
});
function slidechange() {
$('#kenburns-slideshow').empty();
$('#kenburns-slideshow').Kenburns({
images: [
"http://static2.wikia.nocookie.net/__cb20070903093660/nonciclopedia/images/thumb/c/cf/Fini.jpg/200px-Fini.jpg",
"http://www.caffettieragiornaliera.it/wp-content/gallery/signor-boh/boh-facebook.gif",
"http://www.lanostratv.it/wp-content/uploads/2013/01/rai-boh-flop-facchinetti.jpg",
],
scale:0.75,
duration:8000,
fadeSpeed:1200,
ease3d:'cubic-bezier(0.445, 0.050, 0.550, 0.950)',
onSlideComplete: function(){
$('#slide-title').html(titles[this.getSlideIndex()]);
},
onLoadingComplete: function(){
$('#status').html("Loading Complete");
}
});
};
It does not work without errors.
<div id="kenburns-slideshow"><div id='foo'></div></div>
Inserted new div inside. Leaving his parent as placeholder.
Then on button click
Completley remove old div.
$('#foo').remove();
Then create same element and attach Kenburns library to it.
$("<div></div>").attr("id","foo").appendTo("#kenburns-slideshow").Kenburns({});
(with your settings in example)
As Marius wrote:
var titles = ["Epic Day at Refugio",
"Colors of Spring",
"First Flowers",
"Magic Hour at Sands Beach",
"Coal Oil Point",
"Hope Ranch Views"];
$(document).ready(function() {
$("<div></div>").attr("id","newdiv").appendTo("#kenburns-slideshow").Kenburns({
images: [
"http://www.toymakerlabs.com/kenburns/images/image0.jpg",
"http://www.toymakerlabs.com/kenburns/images/image1.jpg",
"http://www.toymakerlabs.com/kenburns/images/image2.jpg",
"http://www.toymakerlabs.com/kenburns/images/image3.jpg",
"http://www.toymakerlabs.com/kenburns/images/image4.jpg",
"http://www.toymakerlabs.com/kenburns/images/image5.jpg" ],
scale:0.75,
duration:8000,
fadeSpeed:1200,
ease3d:'cubic-bezier(0.445, 0.050, 0.550, 0.950)',
onSlideComplete: function(){
$('#slide-title').html(titles[this.getSlideIndex()]);
},
onLoadingComplete: function(){
$('#status').html("Loading Complete");
}
});
$('#mybutton').click(slidechange);
function slidechange() {
$('#kenburns-slideshow #newdiv').remove();
$("<div></div>").attr("id","newdiv").appendTo("#kenburns-slideshow").Kenburns({
images: [
"http://static2.wikia.nocookie.net/__cb20070903093660/nonciclopedia/images/thumb/c/cf/Fini.jpg/200px-Fini.jpg",
"http://www.caffettieragiornaliera.it/wp-content/gallery/signor-boh/boh-facebook.gif",
"http://www.lanostratv.it/wp-content/uploads/2013/01/rai-boh-flop-facchinetti.jpg",
],
scale:0.75,
duration:8000,
fadeSpeed:1200,
ease3d:'cubic-bezier(0.445, 0.050, 0.550, 0.950)',
onSlideComplete: function(){
$('#slide-title').html(titles[this.getSlideIndex()]);
},
onLoadingComplete: function(){
$('#status').html("Loading Complete");
}
});
};
});
See the above solution at: http://jsfiddle.net/s4C5K/3/

Categories