I am trying to make a popover using bootstrap and placing dynamic content from PHP into it (HTML code).
I have the following code:
<a class="psprn"
href="'.$prnUrl.'"
data-toggle="popover"
data-content="'.$prnName.'"
data-pspicture="'.$prnImage.'"
data-psrank="'.$prnRank.'"
data-psvideo="'.$prnVideos.'">'.$prnName.'</a>
This anchor its a link for users, so I can have 2,3,4 (and so on) users.
This anchor is placed on a 'foreach' Yii app, so he have dynamic content (to have specific image, link, rank, video, content).
I have this js code:
$('[data-toggle="popover"]').hover(function () {
var psrank = $(this).attr("data-psrank");
var psvideo = $(this).attr("data-psvideo");
var pspicture = $(this).attr("data-pspicture");
var pscontent = $(this).attr("data-content");
// console.log(psrank);
// console.log(psvideo);
// console.log(pspicture);
// console.log(pscontent);
$('[data-toggle="popover"]').popover({
trigger: 'hover',
template:
'<div class="ps-placeholder>'+
'<div class="picture">'+
'<img src="prnImage">'+
'</div>'+
'<div class="footy">'+
'<p>$prnName</p>'+
'<span>Rank: $prnRank Videos: $prnVideos</span>'+
'</div>'+
'</div>',
});
});
But something goes wrong. I cannot place the values of data-attributes on the tooltip template.
Infos:
Bootstrap v4.0.0-alpha.4
jQuery v2.2.3
What you currently have won't work. Your variable names get interpreted as strings. You need to replace your " with ` symbol, then you're able to use ${someVariable} within your string.
Here is a basic example.
//Your dynamic content
var catImage = "http://n-z.tv/wp-content/uploads/2017/08/cat-1024x683.jpg";
var message = "Hey this is some dynamic content";
var title = "Some Dynamic Content"
//Create the string and insert it into the body (or the "template" for you)
document.body.innerHTML = `
<div>
<h3>${title}</h3>
<img src="${catImage}"/>
<p>${message}</p>
</div>
`
img {
width: 100px;
}
You could take this a bit further by creating a function that handles this.
let generateDynamicContent = function(title, imageSrc, message){
return `<div>
<h3>${title}</h3>
<img src="${imageSrc}"/>
<p>${message}</p>
</div>
`
}
let dynamic = document.getElementById("dynamic");
let container = document.getElementById("container");
let imageSrcs = [
"https://404store.com/2017/08/19/cat-wallpaper-1024.jpg",
"https://fanparty.ru/fanclubs/cats/gallery/534626_cats.jpg",
"http://n-z.tv/wp-content/uploads/2017/08/cat-1024x683.jpg"
];
let counter = 0;
dynamic.addEventListener("click", function(){
let content = generateDynamicContent(
`Dynamic title #${++counter}`,
imageSrcs[counter%imageSrcs.length],
`Dynamic content #${counter}`
)
container.innerHTML = content;
});
img {
width: 100%;
max-width: 300px;
height: auto;
}
<button id="dynamic">Click me for dynamic content</button>
<div id="container"></div>
Related
I have 2 variables contain data i need to call in HTML based on js logic, can you check and fix code for me what i am missing.
${specialprice} and ${price}
I need javascript condition to be define in javascript file and call it in html. ( JS file already connected to html )
What i need is to complete this logic is if ${specialprice} contain any value then show it together with ${price}
if is empty then show only ${price}.
condition in JS File:
hasspecialprice() {
if(${specialprice} != ''){
var data = "<p class="specialprice">"۔${specialprice}",-</p>
<p class="price"><span class="visibleprice">"۔${price}",-</span></p>"
}
else
{
var data = "<p class="price"><span class="visibleprice">".${price}",-</span></p>"
}
}
Call this function in HTML:
<div class="priceplace">
<script>hasspecialprice();</script>
</div>
Here's an example of how you could change the content of a div dynamically using js. The important thing to note (besides the corrected syntax) is that I selected the output-target in js and then updated it's content based on the relevant values.
// select the form used for the demo
const form = document.querySelector('form');
// select the output div
const target = document.querySelector('.priceplace');
// define our example data
const data = {
price: 0,
specialprice: 0
};
// when a formfield is changed, we change our example data and update the output
form.onchange = ({ target: { value, name } }) => {
data[name] = value;
hasspecialprice(data.price, data.specialprice);
};
function hasspecialprice(price, specialprice) {
// using a ternary expression is equivalent to a simple if/else
// we change the output's html based on the condition
target.innerHTML = specialprice !== ''
? `<p class="specialprice">${specialprice},-</p>
<p class="price"><span class="visibleprice">${price},-</span></p>`
: `<p class="price"><span class="visibleprice">${price},-</span></p>`
}
<form>
Specialprice:
<input name="specialprice">
Price:
<input name="price">
</form>
<div class="priceplace" style="border: 1px solid black; height: 16px"></div>
In Javascript code you dont need to use the ${} statement. The ${} only uses when you need to concatenate string with variables. You only need to remove this from your if statement. You could improve to use
hasspecialprice() {
if(specialprice != ''){
var data = "<p class="specialprice">"۔${specialprice}",-</p>
<p class="price"><span class="visibleprice">"۔${price}",-</span></p>"
}
else
{
var data = "<p class="price"><span class="visibleprice">".${price}",-</span></p>"
}
}
If have an way to call the hasspecialprice() function then you must try this.
hasspecialprice() {
const inputDiv = document.getElementsByClassName("priceplace");
if(${specialprice} != ''){
var pElement = document.createElement('p'); // CREATING AN ELEMENT
pElement.className += "specialprice"; // ADDING CLASSE TO IT
pElement.innerText = specialprice; // ADDING DATA TO IT
var secondPElement = document.createElement('p');
secondPElement.className += "price";
var spanElement = document.createElement('span');
spanElement.className += "visibleprice";
spanElement.innerText = price;
inputDiv.append(pElement);
secondPElement.appendChild(spanElement);
inputDiv.append(secondPElement);
}
else{
var secondPElement = document.createElement('p');
secondPElement.className += "price";
var spanElement = document.createElement('span');
spanElement.className += "visibleprice";
spanElement.innerText = price;
secondPElement.appendChild(spanElement);
inputDiv.append(secondPElement);
}
}
I write a function to append some HTML code to page like below:
function addGiftList(className, imgURL, Kind) {
var $li = $('<li class="' + className + '">');
var $img = $("<img>", { src: imgURL })
var $br = $("<br/>");
var $input = $('<input >', { type: 'radio', name: 'gift', kind: Kind });
var $label = $("<label>").text("Test");
$li.append($img);
$li.append($br);
$li.append($input);
$li.append($label);
return $li;
}
All this will append to a div with className cycle-slideshow then I call $('.cycle-slideshow').cycle();, but nothing happens. Does anyone know why?
Can I create HTML elements with javascript then call jQuery cycle plugin?
HTML
<button>append</button>
<div class="myslider composite-example" data-cycle-fx="scrollHorz" data-cycle-slides="> div" data-cycle-timeout="2000">
<div>
<img src="http://malsup.github.io/images/p1.jpg" width=100%>
<div class="cycle-overlay">first image</div>
</div>
<div>
<img src="http://malsup.github.io/images/p2.jpg" width=100%>
<div class="cycle-overlay">second image</div>
</div>
</div>
CSS
body {
width: 200px;
margin: auto;
}
img {
width: 200px;
}
JS
// first call cycle
$('.myslider').length > 0 && $('.myslider').cycle();
function addGiftList(className, imgURL, Kind) {
var $div = $('<div class="' + className + '">');
var $img = $("<img>", {
src: imgURL
})
var $input = $('<input >', {
type: 'radio',
name: 'gift',
kind: Kind
});
var $label = $("<label>").text("Test");
$div.append($img);
$div.append($input);
$div.append($label);
// dynamically adding slider: this is a plugin method see documentation
$('.myslider').cycle('add', $div);
return;
}
// dynamic add button for example
$('button').on('click', function() {
// add function for example
addGiftList('myclass cycle-slide', 'https://placeholdit.imgix.net/~text?txtsize=15&txt=image%20added&w=200&h=150&txttrack=0');
})
Please see this link of my codepen. I have solved your problem.
http://codepen.io/prashen/pen/PNPbRR
I have a people section on a website I'm building which uses isotope for filtering. When I click on a person I want to show their full info on the right. When the click happens I grab the id and store it as a variable. I then have variables named to match up with the grabbed IDs.
How do I use the grabbed ID to target the variables stored in my js file? Currently it only prints out the ID grabbed from the clicked div.
var userOne = "<p>userOne info<p>";
var userTwo = "<p>userTwo info<p>";
var userThree = "<p>userThree info<p>";
$('.item').on("click", function(){
var id = $(this).attr('id'); // this grabs the ID of the div eg userOne
var printId = id; //trying to change the variable so I can use it
$('.bio').html(printID); //this is where it should print out
});
You can't access a variable name like that, instead what you can do is to access a object's property with a dynamic key
Assuming the variables userOne/userTwo are in the global scope, you can use the bracket notation like
var userOne = "<p>userOne info<p>";
var userTwo = "<p>userTwo info<p>";
var userThree = "<p>userThree info<p>";
$('.item').on("click", function () {
var printId = window[this.id];
$('.bio').html(printID);
});
another option is to store those values as properties of an object
var user = {
userOne: "<p>userOne info<p>",
userTwo: "<p>userTwo info<p>",
userThree: "<p>userThree info<p>"
};
$('.item').on("click", function () {
var printId = user[this.id];
$('.bio').html(printID);
});
Try
html
<div class="item" data-user="<p>userOne info<p>"></div>
js
$(".item").on("click", function(e) {
$(".bio").html($(this).data("user"))
})
$(".item").on("click", function(e) {
$(".bio").html($(this).data("user"))
})
div:not(.bio) {
border:1px dotted grey;
width: 24px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="item" data-user="<p>userOne info<p>">1</div><br />
<div class="item" data-user="<p>userTwo info<p>">2</div><br />
<div class="item" data-user="<p>userThree info<p>">3</div><br />
<div class="bio"></div>
Im fairly new to javascript and i'm trying to do a simple function where my div can be changed with a click of a link. Everything works fine except for when I click on my first link again, it stops working. The others continue to work...
Here is my code...hope someone can help me! Thanks!
<script>
function changedivVIDEO(){
var div = document.getElementById("fw14video");
div.innerHTML = "<div id='main2'>Hello</div>";
}
function changedivCAMPAIGN(){
var div = document.getElementById("fw14campaign");
div.innerHTML = "<div id='main3'>Hello</div>";
}
function changedivRUNWAY(){
var div = document.getElementById("fw14campaign");
div.innerHTML = "<div id='main4'>Hello</div>";
}
</script>
<div id="main">
<div id="fw14video"></div>
<div id="fw14campaign"></div>
<div id="fw14runway"></div>
<div id="fw14runway"></div>
</div>
<p><h3>VIDEO</h3></p>
<p><h3>CAMPAIGN</h3></p>
<p><h3>RUNWAY</h3></p>
<p><h3>ACCESSORIES</h3></p>
</div>
I made an example that fills in the details I think are missing:
<div id="fw14video"></div>
<div id="fw14campaign"></div>
changediv1
changediv2
changediv3
<script>
function changediv1(e){
var div = document.getElementById("fw14video");
div.innerHTML = "<div id='main2'>div1</div>";
e.preventDefault();
}
function changediv2(e){
var div = document.getElementById("fw14campaign");
div.innerHTML = "<div id='main3'>div2</div>";
e.preventDefault();
}
function changediv3(e){
var div = document.getElementById("fw14campaign");
div.innerHTML = "<div id='main4'>div3</div>";
e.preventDefault();
}
</script>
This works as intended. I am using e.preventDefault() to make it not follow the links, and set text different so you can tell which got clicked. Some questions:
do you mean for the IDs to be different?
how did you bind your functions to the links? (I used onclick.)
I think this:
function changedivRUNWAY(){
var div = document.getElementById("fw14campaign");
div.innerHTML = "<div id='main4'>Hello</div>";
}
Should be:
function changedivRUNWAY(){
var div = document.getElementById("fw14runway");
div.innerHTML = "<div id='main4'>Hello</div>";
}
As a starter...and then if nothing else is missing in the code you posted there's a lose < /div> tag.
In the below code "objTo" is a div to which i need to insert multiple number of div.
when i use the code for the first time its working.but on the next time its overwriting the existing code.
<script>
var divtest= document.createElement("div");
divtest.innerHTML = "<div>new div</div>"
objTo.appendChild(divtest)
</script>
Where am i going wrong?
I have made a very simple working version for you :
http://jsfiddle.net/hQKy9/
Multiple clicks works the whole time :
Script
function addDiv() {
var objTo = document.getElementById('container');
var divtest = document.createElement("div");
divtest.innerHTML = "new div";
objTo.appendChild(divtest);
}
Html
<div id="container"></div>
<input type="button" onclick="addDiv();" value="Click here to add div"/>
Even through Marc gave the ans before
I found it we can do more like adding ID/Class and CSS like the following way I did
const newChild = document.createElement('div');
newChild.id = 'newly_content';
newChild.innerHTML = `
<p style="font-size: 30px;padding: 200px 0px 10px 0px;">
A new content has been created!
</p>
`;
document.getElementById('ItemID').appendChild(newChild);