Best way to Programatically write HTML [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
What would be the best way to go about programatically writing many lines of HTML in the following format:
<div class="grid-item"> <img src="gifs/image-GLITCH.gif" alt="image-GLITCH"/> </div>
<div class="grid-item"> <img src="gifs/image.gif"
alt="image"/> </div>
<div class="grid-item"> <img src="gifs/image-GLITCH.gif"
alt="image-GLITCH"/> </div>
The end result is a grid of gifs where the center column contains a normal image, while the left and right columns contain "GLITCH" versions of the image.
Desired end result: many many rows of the following:
https://i.stack.imgur.com/nG08z.jpg
I've thought about using php like:
$images = glob("gifs/*.gif}");
foreach($images as $image) {
echo <div class="grid-item"> <img src=$image alt=""/> </div>
}
Please note that the above is not the exact php I would use, I don't know how to exclude search strings with glob (I believe you can't do that). But this question is meant to ask:
"What is the best way to programatically write html in order to create a grid of images like that contained in the attached image." [i.e this question is not about the actual code to write, but instead what method of writing code should be used: javascript? php?]

The best way to go about this would definitely be with PHP (or a different server-side language). And for that matter, you can completely take glob() out of the equation; you don't want to output based on how many images you have, you want to output a fixed number of images so that it results in the pattern you desire.
First, let's take a look at your raw HTML:
<div class="grid-item">
<img src="gifs/image-GLITCH.gif" alt="image-GLITCH" />
</div>
<div class="grid-item">
<img src="gifs/image.gif" alt="image" />
</div>
<div class="grid-item">
<img src="gifs/image-GLITCH.gif" alt="image-GLITCH" />
</div>
Every second row alternates. The only difference is the <img> src and alt.
Now let's say you have a total of 33 of these (start with a glitch and ending with a glitch), giving a 'nice' number. That's really easy to set up in a PHP loop, using modulo. All you need to do is check whether the variable in your loop divided by your desired 'glitch insertion' offset (every second image in my example) has a remainder or not:
<?php
$image_count = 33;
for ($i = 0; $i < $image_count; $i++) {
if ($i % 2 == 0) {
echo '<div class="grid-item"><img src="gifs/image-GLITCH.gif" alt="image-GLITCH"/></div>' . PHP_EOL;
} else {
echo '<div class="grid-item"><img src="gifs/image.gif" alt="image"/></div>' . PHP_EOL;
}
}
Now you have all of the images outputted correctly, just as with the HTML snippet above.
Also, don't forget your quotation marks around your string!
This can be seen working here:
<div class="grid-item"><img src="gifs/image-GLITCH.gif" alt="image-GLITCH"/></div>
<div class="grid-item"><img src="gifs/image.gif" alt="image"/></div>
<div class="grid-item"><img src="gifs/image-GLITCH.gif" alt="image-GLITCH"/></div>
...

Are you after a javascript solution for this?
(function($) {
var imageUrl = "gifs/image.gif";
var markup = glitichify(imageUrl);
$(markup).appendTo($elementToAppendThisTo);
function glitichify(imageUrl) {
var imageUrlParts = imageUrl.split(".");
var glitchImageUrl = imageUrlParts[0] + "-GLITCH" + imageUrlParts[1];
var imageUrls = [glitchImageUrl, imageUrl, glitchImageUrl];
var imageMarkup = imageUrls.map(function(imageUrl, index) {
return '<div class="grid-item"> <img src="' + imageUrl + '" alt="image"/> </div>';
});
return imageMarkup.join("");
}
})(jQuery);

If you dont use an UI framework like React or Vue and no html engine like pug to generate img tags out of a loop you could do it with js. At least the place where you get your images counts. If you want to include your images dynamically from your local folder you should write a server side script to get an array of your images and then you could pass it to js or use it with your server side lang like php.
var data = ['https://picsum.photos/300?random', 'https://picsum.photos/300?random', 'https://picsum.photos/300?random'],
section = document.querySelector('section');
for (var i = 0; i < data.length; i++) {
var img = document.createElement('img');
img.src = data[i];
section.appendChild(img);
}
section {
border: 1px solid #000;
min-width: 50px;
min-height: 50px;
}
<section></section>

Related

Insert image src into Javascript Array by Class Name

I'm trying to create a JavaScript that will randomize images on page refresh. I'm not really familiar with JS so I've been having a bit of trouble.
I've succeeded in building a successful program by hard coding the image url sources into the JS array, but this is not a possibility for what I am coding this for because the user will dictate what set of images will display. The user will not have access to the JS. So the array would get the image sources from the html. What I've been trying to do is use "getElementByClassName" and insert into the array by for loop. But it doesn't seem to be working. I'm sure there is a more efficient way to do this as well, so feel free to enlighten me.
Here is the code I have so far:
<!-- Images to put into JS Array -->
<img class="header" src="/image1.jpg" style="display: none;" />
<img class="header" src="/image2.jpg" style="display: none;" />
<img class="header" src="/image3.jpg" style="display: none;" />
<!-- Image placeholder -->
<img src="/image1.jpg" id="rotate" />
And the JavaScript in a separate document:
// Javascript code
window.onload = chooseHeader;
var imgs = document.getElementsByClassName("header");
var headers = new Array();
for (var i = 0; i < imgs.length; i++) {
headers.push(imgs[i].src);
}
function chooseHeader() {
rand = Math.floor((Math.random() * headers.length));
document.getElementById("rotate").src = headers[rand];
}
Any advice will be appreciated!
Your code is probably running before the DOM has loaded.
You don't actually need an Array for this, and since getElementsByClassName returns a "live list", you can fetch the images before they exist, and they'll appear when they're loaded in the document.
So if that's the case, a solution is to get the src directly from imgs.
window.onload = chooseHeader;
// live list
var imgs = document.getElementsByClassName("header");
function chooseHeader() {
var rand = Math.floor((Math.random() * imgs.length));
document.getElementById("rotate").src = imgs[rand].src;
}
<img class=header src="https://dummyimage.com/50/f00/fff.jpg">
<img class=header src="https://dummyimage.com/50/0f0/fff.jpg">
<img class=header src="https://dummyimage.com/50/00f/fff.jpg">
<br><br>
Rotate:
<br><br>
<img id=rotate src="">

How to dynamically swap images without reloading the page

I want to create a scroll horizontal for my product page, I have done it in the past, so i have an idea on how to proceed, but this time I want the image clicked to be a bigger size for example 600x600 while all the other images on the bottom of that one with the size 100x100. Have an arrow left right on the side of the big image, and if the arrow is pressed left/right swap that big picture with the previous/next one from the ones in the small size 100x100. Those images are set using php as they are in the server, this is the part that im finding hard aswell I dont know how I would use javascript to alter the images from the php file.
PHP code to get the images
$imgSet = "<img src='../ProductImages/$pID.jpg' class='image' onclick='openNav()'>";
$imgZoom = "<img src='../ProductImages/$pID.jpg' width='600px' height='600px'>";
$pInfo = "nothing for now";
$pDetails = $row['PROD_DETAILS'];
$sql = ("SELECT * FROM CHILD_IMG WHERE PROD_ID = '$pID';");
$getQuery = $connection->query($sql);
while($row = $getQuery->fetch_array()){
$childID = $row['ID'];
$parentID = $row['PROD_ID'];
$childName = $parentID . "_".$childID.".jpg";
$childImg .= "<img src='../ProductImages
/ChildImages/$childName' class='imgBotSize' onclick='openNav()'>";
Child images all the ones on the bottom of the big image
}
Javascript
function openNav() {
document.getElementById("flow").style.height = "100%";
}
function closeNav() {
document.getElementById("flow").style.height = "0%";
}
HTML
<div id="flow" class="overlayImgContainer">
<a class="closebtn" onclick="closeNav()">×</a>
<div class="overlay-img-content">
<a><?php echo $imgZoom;?></a>
<div class="imgSlideGroup">
<a><?php echo $childImg;?></a>
</div>
</div>
<div class="arrowBtn" style="right: 40px">
<img src="../arrow-right-white.png" width="70px" height="120px">
</div>
<div class="arrowBtn" style="left: 40px">
<img src="../arrow-left-white.png" width="70px" height="120px">
</div>
</div>
If you have HTML like below
<div class="leftArrow"></div>
<div>
<img src="../smaller.jpg" class="selectedImage">
</div>
<div class="rightArrow"></div>
And in JS you can select the clicked image and reset the url to bigger image and change the style of the image as below.
var selectedImage = document.querySelector('.selectedImage');
selectedImage.onclick = function(){
selectedImage.src = '../bigger/jpg';
selectedImage.style.height = '400px';
selectedImage.style.width = '300px';
}
Hope this sample code will give some hint

Sorting HTML divs

I have a database table with a list of images. Each image also has data attached, like a name and value. Using this table, I create HTML code with PHP to make a grid on the screen, each with an image/name/value from the table.
This is my PHP that generates the HTML:
//Makes a div for each item in table
Echo "<li id=div" . $i . ">";
//Content for single grid block
Echo '<center><h3 id="credits' . $i . '">' . $credit_value . " credits" . '</h3></center>';
Echo "<img id='item" . $i ."' src= '$new_link' title='$row[Item_Name]' class='clickableImage' alt='$just_name' data-creditvalue='" . $credit_value . "' data-imagenumber='" . $i . "'border=0 style='position: center; top: 0; left: 0;'/>";
Echo '<center><h3 id="quality">' . $quality . '</h3></center>';
Echo '</li>';
This makes each div named "div1", "div2" etc. In the //content section, printed with the image is data-imageName=$imageName and data-imageValue=$value, though I should be able to attach those to the divs holding the content as well.
What I want to do is add buttons at the top of my page which will sort the image grid by categories. It is currently loaded in order of the items in the database table, but for example, I would have a button that could be clicked after the grid is loaded, which changes the orders of all the divs, so they are in alphabetical order, or lowest->highest valule.
How can I do this?
EDIT: Here is an example of the html generated by the above code.
<li id="div2">
<center>
<h3 id="credits2">108 credits</h3>
</center>
<div style="position: relative; left: 0; top: 0;">
<img id="item2" src="http://steamcommunity-a.akamaihd.net/economy/image/fWFc82js0fmoRAP-qOIPu5THSWqfSmTELLqcUywGkijVjZYMUrsm1j-9xgEObwgfEh_nvjlWhNzZCveCDfIBj98xqodQ2CZknz56P7fiDz9-TQXJVfdSXfgF9gT5DBg-4cBrQJnv8eMDKgnutIGTZeEpYt8dH5LTU_ePNwj-uE9s1aZVepTb9Czu33zpJC5UDL2Z8FjG/155fx118f" title="AK-47 | Blue Laminate (Minimal Wear)" class="clickableImage" alt="AK-47 | Blue Laminate " data-creditvalue="108" data-imagenumber="2" border="0" style="position: center; top: 0; left: 0;">
<img src="images/tick.png" id="tick2" class="hidden" style="position: absolute; top: 0px; left: 70%;">
</div>
<center>
<h3 id="quality">Minimal Wear</h3>
</center>
</li>
It's pretty easy to sort nodes with jQuery (and in pure JS actually too). You need to use sort methods which delegates to Array.prototype.sort, just provide custom comparator functions.
In your case you want to be able to sort by string title as well as by number, so I would create two separate functions and use them depending on what button was clicked:
<button onclick="sort('title', 'string')">Sort by name</button>
<button onclick="sort('data-creditvalue', 'number')">Sort by value</button>
and sort function will be
var comparators = {
string: function(a, b) {
return a.localeCompare(b);
},
number: function(a, b) {
return Number(a) - Number(b);
}
};
function sort(attr, type) {
var $container = $('ul'),
$li = $container.find('li');
$li.sort(function(a, b) {
var aVal = $(a).find('img').attr(attr),
bVal = $(b).find('img').attr(attr);
console.log(aVal)
return comparators[type](aVal, bVal);
}).appendTo($container);
}
Demo: http://plnkr.co/edit/lLJ0AWlLvwDeInBEIYCb?p=info
Depends where you want to have the sorting done.
Do you want the sorting done on the server or on the client?
SERVER SIDE: Your column headers would need to link back to the server and pass a SQL parameter to update your SQL query. This wouldn't be the prefered way. It would refresh the page every time you sorted.
CLIENT SIDE: You could use a jQuery plugin, like DataTable, to do the sorting.
CLIENT SIDE (Ajax): Here is some good detail already published

use html5 output tag to display javascript variables?

Sorry if this is a silly question, but I've been trying to use AJAX to display my javascript variables in 'real time' with little luck. I'm definitely a beginner though so this could be the problem haha- When I see the AJAX code, it always seems to require an additional url that it refreshes, but I just want to refresh the javascript variables on click.
http://jsfiddle.net/bagelpirate/m9Pm2/
<script>
var one = 0;
var two = 0;
var three = 0;
</script>
<body>
<div id="div_1">
One: <script>document.write(one)</script> |
Two: <script>document.write(two)</script> |
Three: <script>document.write(three)</script>
</div>
<div id="div_2">
<img id="mine" src="https://si0.twimg.com/profile_images/3170725828/ac1d6621fc3c3ecaa541d8073d4421cc.jpeg" onclick="one++;" />
<img id="forest" src="http://blogs.dallasobserver.com/sportatorium/No.%202.png" onclick="two++;" />
<img id="farm" src="https://si0.twimg.com/profile_images/3732261215/bd041d1f0948b6ea0493f90507d67ef2.png" onclick="three++;" />
</div>
</body>
As you can see in the above code, when a user clicks one of the images, I want to increment the count and display it at the top of the page. I found the HTML5 output tag, and was wondering if it's possible to use this to display the javascript variable in real time? Everything I've read seems to imply it can't be done because the output tag only works on forms? Anyway, I figured it couldn't hurt to ask!
Thanks for your time!
You shouldn't use document.write to write to the DOM after it's finished loading. You have tagged your question with jQuery, so I'll assume you can use that to update things. Instead, update the DOM from within your script block. Here is an example that might help you get started.
http://jsfiddle.net/prxBb/
<script type="text/javascript">
$(function() {
var one = 0;
var two = 0;
var three = 0;
$('img#mine').click(function() {
one++;
$('span#one').html(one);
});
$('img#forest').click(function() {
two++;
$('span#two').html(two);
});
$('img#farm').click(function() {
three++;
$('span#three').html(three);
});
});
</script>
<body>
<div id="div_1">
One: <span id="one"></span> |
Two: <span id="two"></span> |
Three: <span id="three"></span>
</div>
<div id="div_2">
<img id="mine" src="https://si0.twimg.com/profile_images/3170725828/ac1d6621fc3c3ecaa541d8073d4421cc.jpeg" />
<img id="forest" src="http://blogs.dallasobserver.com/sportatorium/No.%202.png" />
<img id="farm" src="https://si0.twimg.com/profile_images/3732261215/bd041d1f0948b6ea0493f90507d67ef2.png" />
</div>
</body>
Maybe you should try putting all your variables inside a named object, iterating through it at predefined interval and displaying the values.
var varContainer = {
one:0,
two:0,
three:0
};
jQuery("#div_2 img").on('click',function(){
jQuery.each(varContainer,function(key,value){
//Add key + value to the DOM
if(jQuery("."+key+value).length<1)
jQuery("#div_2").append("<div class='"+key+value+"'></div>");
var newHtmlVal= "<p><span>Var name: "+key+"</span><br><span>Value: "+value+"</span>";
jQuery("."+key+value).html();
});
});
HTML
<div id="div_2">
</div>
Of course the script could be upgraded to look through each variable recursivley in case of nested objects/arrays...
Hope this helps!

Getting the amount of images which are in a specific div

I'm trying to get the amount of images which are stored in the post-content container of each post.
The layout of a post looks like this:
<div class="post">
<div class="post-toolbar">
<div class="post-date">date</div>
<div class="signs">
<div class="hearts">♥</div>
<div><img src="logo.png"></div>
<div><img src="logo2.png"></div>
</div>
<div class="post-title">title</div>
</div>
<div class="post-content">
<img src="image.png">
<img src="image.png">
</div>
</div>
And a Javascript snippet which looks like this:
$('.hearts').live("click",function() {
var amount = $(this).parent().parent().parent().find("img").size();
console.log(amount);
});
At the moment the value of amount is 4.
I'm sure the is a much nicer way to access the .post-content div with jQuery.
$('.hearts').live("click",function() {
var post = $(this).closest('.post'); // will find the first element with the class post up the DOM tree
var amount = $('.post-content img', post).size();
console.log(amount);
});
BTW you should really look into .delegate() and never use .live() again since live is way slower than delegate.
Or even better if you are on jQuery 1.7 or higher use .on().
How about $(this).parents(".post") ?
$('.hearts').live("click",function() {
var amount = $(this).parents(".post").children(".post-content").find("img").size();
alert(amount);
});

Categories

Resources