How to create div cards in html dynamically using javascript & jquery? - javascript

I created this card for design purpose but i want to create html card dynamically using JavaScript or jQuery, means if I pass 5 value in a loop then 5 cards create with same design. How can I do this?
<div class="scrolling-wrapper">
<div class="card">
<img id="card-shopping-cart-icon" src="images/cart.png" alt="">
<img id="card-wishlist-icon" src="images/heart.png" alt="">
<img id="card-image" src="images/motorola_one.jpg" alt="Motorola" class="contain">
<div class="card-text-body">
<p class="card-clock-deals-title">Motorola One Power</p>
<p class="card-clock-deals-detail">RAM 4/6GB ROM 64GB</p>
<p class="card-clock-deals-discounted-price">2000</p>
<p>
<table class="card-clock-deals-timer">
<tr>
<td id="hours">12</td>
<td>:</td>
<td id="minutes">00</td>
</tr>
</table>
</p>
<p class="card-clock-deals-original-price">3000</p>
<p class="card-clock-deals-timer-text">Hrs Left</p>
<p class="card-clock-deals-like-image"><img src="images/heart.png" alt="">(381)</p>
</div </div>
I created this card for design purpose but i want to create html card dynamically using JavaScript or jQuery, means if I pass 5 value in a loop then 5 cards create with same design. How can I do this?

So as I asked you, you're using a database to store the data from the cards right? So all you need is create the connection to the database, then fetch the result with a loop to display one by one the cards.
// Here you need to create your connection to the database with your values
<?php
include 'connection.php';
//Here write your SQL query to get the data from your cards database
$sql = "SELECT * FROM cards";
$result = $conn->query($sql);
?>
// Then we start with the html code to get the data and show the cards
<!doctype html>
<html>
<body>
<h1 align="center">CARDS</h1>
<?php
//Fetch Data form database
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
?>
<div class="scrolling-wrapper">
<div class="card">
<img id="card-shopping-cart-icon" src="images/cart.png" alt="">
<img id="card-wishlist-icon" src="images/heart.png" alt="">
<img id="card-image" src="images/<?php echo $row['RowNameYouWannaGet']; ?>" alt="Motorola" class="contain">
<div class="card-text-body">
<p class="card-clock-deals-title"><?php echo $row['RowNameYouWannaGet']; ?></p>
<p class="card-clock-deals-detail"><?php echo $row['RowNameYouWannaGet']; ?></p>
<p class="card-clock-deals-discounted-price"><?php echo $row['RowNameYouWannaGet']; ?></p>
<p>
<table class="card-clock-deals-timer">
<tr>
<td id="hours"><?php echo $row['RowNameYouWannaGet']; ?></td>
<td>:</td>
<td id="minutes"><?php echo $row['RowNameYouWannaGet']; ?></td>
</tr>
</table>
</p>
<p class="card-clock-deals-original-price"><?php echo $row['RowNameYouWannaGet']; ?></p>
<p class="card-clock-deals-timer-text"><?php echo $row['RowNameYouWannaGet']; ?></p>
<p class="card-clock-deals-like-image"><img src="images/heart.png" alt=""><?php echo $row['RowNameYouWannaGet']; ?></p>
</div>
</div>
<?php
}
}
else
{ echo "No data found" } ?>
</body>
</html>
Hope it helps, you can also find info on Google searching--> Dynamic Tables PHP, MySQL

*ONLY FOR BOOTSTRAP 4 and above HTML CODE BELOW AND FIND "JAVASCRIPT FOR CARDS"
<div class="container row col-12 col-sm-12 justify-content-center" id="parsi">
<div class="card" style="width:18 rem;">
<img class="card-img-top"src="#" alt="">
<div class="card-body">
<h1>This is an card</h1>
<p class="card-text">Lorem ipsum dolor, sit amet consectetur adipisicing
elit. Tempore, repudiandae neque? Placeat harum veniam omnis dolorum
necessitatibus vitae, nisi ducimus illum.</p>
<button type="button" class="btn btn-primary"
onclick="myclick()">Submit</button>
</div>
</div>
</div>
"JAVASCRIPT FOR CARDS" ==>
function myclick(){
var x= prompt("Enter number of cards u want to make","6");
if (x!=null){
var main=document.getElementById("parsi");
let num=parseInt(x);
var i;
const red="Lorem ipsum dolor, sit amet consectetur adipisicing elit. Tempore,
repudiandae neque? Placeat harum veniam omnis dolorum necessitatibus vitae,
nisi ducimus illum.";
var div=[];
for (i=0;i<num;i++){
div.push(document.createElement("div"));
div[i].setAttribute("class","card col-12 col-sm-3 ml-2 mt-3");
div[i].setAttribute("style","width:18 rem;");
const image=document.createElement("img");
image.setAttribute("class","card-img-top");
image.src="#";
div[i].appendChild(image);
var innerDiv=document.createElement("div");
innerDiv.setAttribute("class","card-body");
var h1=document.createElement("h1");
h1.textContent="This is the heading";
var p1=document.createElement("p1");
p1.setAttribute("class","card-text");
p1.textContent=red;
innerDiv.appendChild(h1);
innerDiv.appendChild(p1);
div[i].appendChild(innerDiv);
main.appendChild(div[i]);
}
}
}

I have created jsFiddle demo for this.
https://jsfiddle.net/wer4px80/2/
html:
<div id="scrolling-wrapper"></div>
javascript:
$(document).ready(function(){
var count = 5;
var html = "";
for(i=1;i<=count;i++)
{
html += "<div class='card'>card " + i +"</div>";
html += "<br>";
}
$("#scrolling-wrapper").html(html);
});
Please check if you need to generate more cards you can change the variable value and change html content as per your needs.
You should get dynamic data using ajax from your endpoint which provides you the data stored somewhere in your database you need to render on your page.
Also you can look into handlebars or mustache templating tools for better handling of dynamic content.
Links are given below:
https://mustache.github.io/
https://handlebarsjs.com/

Related

changing button based on bootstrap collapse state

I am using bootstrap.
I have the HTML code below:
<div class="row">
<button id="dog-btn" data-toggle="collapse" data-target="#dog-section" onclick="petToggle()">Show Pet</button>
</div>
<div class="col-12 collapse" id="dog-section">
I have the JS below:
function petToggle() {
var dogDiv = document.getElementById("dog-section");
var dogBtn = document.getElementById("dog-btn");
}
In my website the starting state of dog-section is variable. Sometimes it could be visible sometimes it can be closed. I tried using :hidden and :visible with jquery to get the initial state of the div but it didn't work as it always returned true or always returned false. My desired outcome: if dog-section is hidden because of Bootstrap dropdown I want the button to read Show Pet. If the dog-section is visible, I want it to read Hide Pet.
Can anyone help?
Use a conditional to check if the css is set to visible if it is then set it to hidden.
With jQuery:
To check:
if(dogSection.css('visibility') === 'hidden'){
// make it visible
}else{
// hide it
}
To set visible:
dogSection.css('visibility', 'visible')
To set hidden:
dogSection.css('visibility', 'hidden')
const $btn = $('#dog-btn')
const $dogSection = $('#dog-section')
function petToggle(){
$btn.click(function(){
if($dogSection.css('visibility') === 'hidden'){
$dogSection.css('visibility', 'visible')
$btn.text("Hide Pet Section")
}else{
$dogSection.css('visibility', 'hidden')
$btn.text("Show Pet Section")
}
})
}
petToggle()
#dog-section {
visibility: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<button id="dog-btn" data-toggle="collapse" data-target="#dog-section">Show Pet Section</button>
</div>
<div class="col-12 collapse" id="dog-section">
<img src="https://www.petmd.com/sites/default/files/sleeping-dogs-curled-up.jpg" alt="Sleeping Dog" width="450" height="355">
<img href="">
</div>
Using vanilla Javascript...
Depending on how you are displaying your #dog-section in the DOM you can use one of the following.
if(getComputedStyle(dogSection).getPropertyValue('visibility') === 'hidden')
if(getComputedStyle(dogSection).getPropertyValue('display') === 'none')
if(dogSection.style.visibility === 'hidden';
if(dogSection.style.display === 'none';
Then set it using one of the following:
dogSection.style.setProperty('visibility', 'visible')
dogSection.style.visibility = 'visible'
const btn = document.getElementById('dog-btn')
const dogSection = document.getElementById('dog-section')
function petToggle(){
btn.addEventListener('click', function(){
if(getComputedStyle(dogSection).getPropertyValue('visibility') === 'hidden'){
dogSection.style.setProperty('visibility', 'visible')
btn.textContent = "Hide Pet Section"
}else{
dogSection.style.setProperty('visibility', 'hidden')
btn.textContent = "Show Pet Section"
}
})
}
petToggle()
#dog-section {
visibility: hidden;
}
<div class="row">
<button id="dog-btn" data-toggle="collapse" data-target="#dog-section">Show Pet Section</button>
</div>
<div class="col-12 collapse" id="dog-section">
<img src="https://www.petmd.com/sites/default/files/sleeping-dogs-curled-up.jpg" alt="Sleeping Dog" width="450" height="355">
<img href="">
</div>
Remove the petToggle function. You need to use the collapse events to achieve what you want. Here's documentation.
Since dog-section might be hidden or shown initially, you can check the display style of the section and change button text accordingly.
// check the initial display state of the dog-section
// if it's hidden, set the button text to "Show Pet"
// if it's shown, set the button text to "Hide Pet"
if ($("#dog-section").css("display") === "none") {
$("#dog-btn").text("Show Pet");
} else {
$("#dog-btn").text("Hide Pet");
}
// set the button text to "Hide Pet" when dog-section is shown
$("#dog-section").on("show.bs.collapse", function () {
$("#dog-btn").text("Hide Pet");
});
// set the button text to "Show Pet" when dog-section is hidden
$("#dog-section").on("hide.bs.collapse", function () {
$("#dog-btn").text("Show Pet");
});
<link href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.bundle.min.js"></script>
<div class="container">
<div class="row">
<button id="dog-btn" data-toggle="collapse" data-target="#dog-section">Show Pet</button>
</div>
<div class="row">
<div class="col-12 collapse" id="dog-section">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam quia suscipit amet ex aut. Odit error dolorem tempore, officiis sed, fugit in voluptate laboriosam quas illo ipsa alias magnam! Odit.
</div>
</div>
</div>

How can I access my vue instance when in a v-for loop?

I have a v-for loop
<div v-for="index in 6" :key="index">
<div class="card h-100" style="margin-top: 200px;">
<a href="#">
<img
class="card-img-top"
src="https://i.picsum.photos/id/345/700/400.jpg?hmac=oQMF95pIPaAEnln8qWEjerYF_2lcuFsfl_KnwjHnpXc"
alt
/>
</a>
<div class="card-body">
<h4 class="card-title">
<p>{{ this.itemData[index].name }}</p>
</h4>
<p
class="card-text"
>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet numquam aspernatur!</p>
</div>
<div class="card-footer">
<small class="text-muted">★ ★ ★ ★ ☆</small>
</div>
</div>
</div>
</div>
</div>
I get the following error:
TypeError: Cannot read property 'itemData' of undefined
However, I can reference this same line of code outside of the loop and it will be displayed.
I also get issues when I run this.itemData[0].price, price being a present element in the itemData[0] object. Any help is appreciated!
The error TypeError: Cannot read property 'itemData' of undefined happens because you're using this. prefix within the template, which is not recommended.
I've even found that there's a rule for that in the official ESLint plugin for vue:
https://eslint.vuejs.org/rules/this-in-template.html
Hope it helps!
Relevant CodePen
v-for="index in 6" is going to start at 1:
1, 2, 3, 4, 5, 6.
But arrays start at 0.
If your array contains 6 items, this will fail because itemData[6] does not exist. In fact, if it did not fail, it would still skip the first item in the array, itemData[0].
In your template, change your binding to:
{{ itemData[index - 1].name }}

How to refactor php href links to respond with Modal or popover

I am rewriting some text which is heavy with footnotes in the form
<a id="par170_fn1" href="get_footnote.php?id=118">[1]</a>
The footnotes are organized in a table.
I'm a little confused by the technical flow of executing these refactorings using modal dialog or popovers. It seems that Ajax is inherently part of the process.
I'm a little stuck on the concept of matching the dynamic data where.
This example from the Bootstrap Docs makes sense in general, but I'm missing the bridge that allows my retrieved data to be accounted for in the call.
Plus I don't want to replace the links with buttons.
<div class="modal-body">
<h5>Popover in a modal</h5>
<p>This button triggers a popover on click.</p>
<hr>
<h5>Tooltips in a modal</h5>
<p>This link and that link have tooltips on hover.</p>
</div>
I would appreciate some tips on how to think this through on a fundamental level.
If you create hyperlinks for each footnote as follows:
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit <sub><a class="footnote" href="/footnote.php?id=123">[123]</a></sub>.</p>
Then you can bind a click event using jQuery to fetch the HTML content using AJAX, inject it into a Bootstrap modal and launch the modal.
$('.footnote').on('click', function (event) {
event.preventDefault();
var $modal = $('#footnote-modal');
$.get(event.target.href, function (response) {
$modal.find('.modal-body').html(response);
$modal.modal();
});
});
Here's an example, where I've substitued an AJAX call using $.get with a Promise to illustrate how the code would work.
// For example purposes only
var html = '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas architecto voluptatem, natus temporibus quasi labore repellat laboriosam culpa.</p>';
$('.footnote').on('click', function (event) {
event.preventDefault();
var $modal = $('#footnote-modal');
// For example purposes only
Promise.resolve(html)
.then(function (response) {
$modal.find('.modal-body').html(response);
$modal.modal();
});
// Actual code to call your PHP script
// $.get(event.target.href, function (response) {
// $modal.find('.modal-body').html(response);
// $modal.modal();
// });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit <sub><a class="footnote" href="/footnote.php?id=123">[123]</a></sub>.</p>
<p>Dolorum ducimus quos officia blanditiis expedita <sub><a class="footnote" href="/footnote.php?id=123">[456]</a></sub>.</p>
<!-- Modal -->
<div class="modal fade" id="footnote-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="exampleModalLongTitle">Footnote</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body"></div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
Any questions, just ask.
So, in order to resolve the problem I had to go back and examine some foundational logic.
I created my html in php using echo statements. It was how I originally wrote it, when I was learning about PHP. Time for a refactor. Used html, embedding the small amount of PHP as needed with code tags.
I was using an older version of bootstrap which allowed a functionality which is deprecated in BS4. I didn't realize that functionality was in effect until the previously working code was failing with BS4.
Using the latest BS made me aware of the need for jQuery AJAX. I wanted to stay in vamilla JS, but I realized I understand JS much better than I thought and was then able to use the jQuery docs to get a handle on the remote data being pulled from a PHP GET.
I refactored my php script to return JSON and do the data wrangling on the server end and simply pass the desired data to my js script for populating the modal.
I set up the modal divs, which is actually far simpler than I was complaining about.
I refactored the footnote tags in the database. A simple task using replace functionality in my database tool.
So here's how I resolved my issue:
Refactor the tags to this format:
<sup><a data-toggle="modal" data-target="#footnote-modal" id="par180_fn10" href="footnote.php?id=127">[10]</a></sup>
Format the modal html:
<!-- Modal -->
<div class="modal fade" id="footnote-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<!-- Modal content -->
<div class="modal-content">
<!-- Modal header -->
<div class="modal-header">
<h4 class="modal-title" id="footnoteTitle"></h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<!-- Modal Body -->
<div class="modal-body" id="footnote_detail"></div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Enable the JavaScript
$(document).ready(function(){
$('#footnote-modal').on('show.bs.modal', function(dataString){
//console.dir(dataString.relatedTarget);
var location = dataString.relatedTarget.attributes[3].value;
console.log(location);
$.ajax({
method: "GET",
url: location,
dataType: "json",
success: function(res){
//console.dir(res);
$('#footnoteTitle').html(res.data[0] + res.data[1] +
res.data[2] + res.data[3] + ", Footnote " + res.footnote_no);
$('#footnote_detail').html(res.footnote_text);
}
})
.fail(function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
});
});
});

Dynamic Facebook share button via jQuery

HTML:
<div class="views-row views-row-2 views-row-even">
<div class="sonuc">
<span>lorem ipsum dolor sit amet</span>
</div>
<div class="views-field views-field-nothing">
<span class="field-content">Share</span>
</div> <div class="sonucbg"></div>
</div>
<div class="views-row views-row-2 views-row-even">
<div class="sonuc">
<span>lorem ipsum dolor sit amet 2222</span>
</div>
<div class="views-field views-field-nothing">
<span class="field-content">Share</span>
</div> <div class="sonucbg"></div>
</div>
JS:
$('#share').click(function() {
var product_name = jQuery(".sonuc span").html();
FB.ui({
method: 'feed',
name: product_name,
}, function(response) {
if(response && response.post_id){}
else{}
});
});
When I click my .share button, get popup, its OK. But I want, e.g. click first share button, get that text.
How can I do it?
You need to isolate the instance of .sonuc span within the views-row instance based on which button was clicked
Try this:
$('.share').click(function() {
var product_name = $(this).closest('.views-row').find(".sonuc span").html();
/* FB code */
});
What you currently have will always get the html from the first .sonic contained in the page

jQuery append current div

I have an outter div .listingContainer, I have about 10 of these on the page all with different content in them. When I click the inner div .saveCompare I want to get the html off all the .listingContainer using jQuery var htmlStr = $(this).html();
I am finding it difficult getting the html of the clicked div, I tried .parent and such and it does not seem to work.
Would be grateful if someone point me to the correct dom call, thanks.
<div class="listingContainer grid_9 alpha omega">
<a class="listContent" href="adContent.html">
<div class="listingWrapper">
<div class="grid_8 alpha omega">
<div class="listingContent">
<div class="imgHolder">
<img src="imgs/cars/SearchThumb-10053319.jpg" width="100" height="75">
</div>
<div class="descHolder">
<div id="doneDeal"></div>
<h3>Fancy Car</h3><div class="saveCompare"><strong>+</strong> Compare</div>
<p>Lorem ipsum dolor sit amet, pri ex duis maiorum commune, illud viderer suscipiantur eam an. Dolorum recteque qui in. Pro inani nulla tacimates ex, qu</p>
<span class="listingPrice"><strong>€4,000</strong></span>
<span class="listingDate">Listed: <strong>Today</strong></span>
<span class="listingLocation">Co. Waterford</span>
<span class="listingViews">Viewed: 20 Times</span>
</div>
</div>
</div>
<div class="goTo goTo_unfocus grid_1 alpha omega">
<div class="gotoWrapper">
Click to View
<div class="imgVeiw"></div>
</div>
</div>
</div><!--End listingWrapper-->
</a>
</div>
To get the first parent that matches a specific selector, starting from an element going up, you can use .closest:
$(this).closest(".listingContainer");
This should accomplish what you are asking:
$(".saveCompare​​​").click(function() {
alert($(this).closest(".listingContainer").html());
});​​
$(".saveCompare").click(function(ev){
var listEl = $(this).parents(".listingContainer").first();
//Do what ever you want with listEl. For example listEl.html() ..etc;
});
$(".saveCompare").parents(".listingContainer"​​)​.get(0)
$('.saveCompare').click(function() {
$(this).parents('.listingContainer:first');
});
.listContent is an anchor tag and all the elements inside that. I'm not sure you will get "$('.saveCompare').click". Check this link
http://jsfiddle.net/Zh7HN/1/

Categories