Styling Divs with Javascript Vars - javascript

I'm doing a little experiment trying to randomly place images inside a div using a javascript loop. I've been having some trouble with it.
Here's what I have (simplified):
for(var i = 0; i < 10; i++)
{
var top = random(-20, 20);
var left = random(-20, 20);
document.write(
<div class="one" style="\"left:" + left + ";\"">
<img src="hein.png"/>
</div>
);
}
The goal being to generate some top and left values, and every itteration display a new image with these generated values. I know it's a syntax error with the style="". But nothing I've tried has worked
How can I get this working.

You meed to wrap the whole of the document.write output in quotes, like this:
document.write('<div class="one" style="left:"' + left + ';"><img src="hein.png"/></div>');

You should first consider using a JavaScript library like jQuery. This will simplify your work.
Let's say you have this markup
<div id="image-container">
</div>
Include jQuery in you markup
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
From JavaScript you would do this, after you've included jQuery in your markup
for(var i = 0; i < 10; i++) {
var top = random(-20, 20);
var left = random(-20, 20);
$('#image-container').append('<img src="hein.png" style="position: absolute; top: '+top+'; left : '+left +';" />');
}

You forgot the quotes in document.write and you are escaping wrong characters inside of it
document.write(
"<div class=\"one\" style=\"left:" + left + ";\">
<img src=\"hein.png\"/>
</div>"
);

You have forgotten to quote the string in the document.write call. Also you forgot the unit on the measurement.
for(var i = 0; i < 10; i++) {
var top = random(-20, 20);
var left = random(-20, 20);
document.write(
'<div class="one" style="left:' + left + 'px;top:' + top + 'px">' +
'<img src="hein.png"/>' +
'</div>'
);
}

Using PHP Instead:
<?php
// Middle coords of my div
$top = 200;
$left = 350;
for($i = 0; $i < 20; $i += 1)
{
$tran = rand(-130,170);
$lran = rand(-300,270);
// Fix line breaks
$top = $top - 49;
echo '<div style="position:relative;
display: block;
height: 49px;
width:49px;
left:' . ($left + $lran) . 'px;
top:' . ($top + $tran) . 'px;
">' . '<img src="img.png"/>' . '</div>';
}
?>
Awesome! Thanks for the help with the string syntax!

Related

use a eventlistner click value for looped output from a function

Here's the code I have so far but it all makes the first baloon change and id like each div id clicked to supply the output to the div clicked. Not sure if I can combine this in an easy function or should I make 1 function for each div separately.
document.getElementById("baloon1").addEventListener("click", eggBasket);
document.getElementById("baloon2").addEventListener("click", eggBasket);
document.getElementById("baloon3").addEventListener("click", eggBasket);
function eggBasket(){
var dispImages = new Array ();
dispImages[1] = "images/1.png";
dispImages[2] = "images/2.png";
dispImages[3] = "images/3.png";
dispImages[4] = "images/4.png";
var rnd = Math.floor( Math.random() * dispImages.length );
if( rnd == 0 ) {
rnd =1;
}
if (document.getElementById("baloon1")){
document.getElementById("baloon1").innerHTML = "<img src='" + dispImages[rnd] + "'/>";
}
else if (document.getElementById("baloon2")){
document.getElementById("baloon2").innerHTML = "<img src='" + dispImages[rnd] + "'/>";
}
else if (document.getElementById("baloon3")){
document.getElementById("baloon3").innerHTML = "<img src='" + dispImages[rnd] + "'/>";
}
}
This is all in a scripts.js file being called to the php page.
Corrected the function name
Heres the html
echo'
<div id="baloon1">
<img src="' . $randomImage . '">
</div>
<div id="baloon2">
<img src="' . $randomImage2 . '">
</div>
<div id="baloon3">
<img src="' . $randomImage2 . '"/>
</div>';
Here, we bind to each egg, same method.
document.querySelectorAll('.egg').forEach(egg => {
egg.addEventListener("click", (event) => {
console.log(`you clicked on ${event.target.id}`);
});
});
<div id="egg1" class="egg"> Egg1 </div>
<div id="egg2" class="egg"> Egg1 </div>
<div id="egg2" class="egg"> Egg3 </div>
If you want each baloon to show a random image when clicked try something like this:
[].slice
// find all divs containing an id containing baloon
.call(document.querySelectorAll('[id*=baloon]'))
// loop through all found divs
.map(function(baloon) {
// array of images to be randomized
var images = [
'https://unsplash.it/100/?random=1',
'https://unsplash.it/100/?random=2',
'https://unsplash.it/100/?random=3',
'https://unsplash.it/100/?random=4'
];
// pick a random image
var image = images[Math.floor(Math.random() * images.length)];
// add image to current baloon div
baloon.innerHTML = '<img src="' + image + '">';
// add click listener to baloon div
baloon.addEventListener('click', function() {
// pick a new random image
var image = images[Math.floor(Math.random() * images.length)];
// add new image to current baloon div
baloon.innerHTML = '<img src="' + image + '">';
})
})
[id*="baloon"] {
width: 100px;
height: 100px;
float: left;
margin: 10px;
border: 1px solid #ccc;
}
<div id="baloon1"></div>
<div id="baloon2"></div>
<div id="baloon3"></div>
In response to comment (please note I'm not an expert on php)
<?php
// print out images from dir to js array
$images = array();
foreach (glob("/IMAGEPATH/*.{jpg,png,gif}", GLOB_BRACE) as $filename) {
$images[] = $filename;
}
echo "<script>var images=" . json_encode($images) . "</script>";
?>
From what I understand you are looking for, you want to pass the baloon's div ID to Basket to only modify that div.
document.getElementById("baloon1").addEventListener("click", function(){Basket('baloon1');});
document.getElementById("baloon1").addEventListener("click", function(){Basket('baloon2');});
document.getElementById("baloon1").addEventListener("click", function(){Basket('baloon3');});
function Basket(divId){
var dispImages = new Array ();
dispImages[1] = "images/1.png";
dispImages[2] = "images/2.png";
dispImages[3] = "images/3.png";
dispImages[4] = "images/4.png";
var rnd = Math.floor( Math.random() * dispImages.length );
if( rnd == 0 ) {rnd =1;}
document.getElementById(divId).innerHTML = "<img src='" + dispImages[rnd] + "'/>";
}
You can get all elements which id start with baloon like
var allElements = document.querySelectorAll('[id^="baloon"]')
for (var i = 0; i < allElements.length; i++) {
allElements[i].addEventListener('click', eggBasket)
}
function eggBasket(){
console.log('clicked')
}
<div id="baloon1" >baloon1</div>
<div id="baloon2" >baloon2</div>
<div id="baloon3" >baloon3</div>

Loop of html using javascript

i am new on using of JavaScript on looping of html. I have this code below that i am working at. In this problem of mine i have 2 loop the main and the card-body loop. As you can see in the code First I need to loop the main to create a card and then at the body i need also to loop it because of the data content. I have also working code below but as you can see at the card-body its not looping anymore but static data that I inputted.
Problem
for (var i = 0; i < dataLength; i++) {
var docsLength = data.data[i].resultData;
var title = data.data[i].resultData[i].Type.Description;
var card = '<div class="card"> <div class="card-header bg-success"><h3 class="card-title">' + title + ' </h3 ></div> <div class="card-body">'; for (var a = 0; a < 2; a++) { "a" } ' </div>' +
'</div >';
$("#card_documents > .card-body").append(card);
}
Working
for (var i = 0; i < dataLength; i++) {
var docsLength = data.data[i].resultData;
var title = data.data[i].resultData[i].Type.Description;
var card = '<div class="card"> <div class="card-header bg-success"><h3 class="card-title">' + title + ' </h3 ></div> <div class="card-body">' +
"asdasdasdasd" +
'</div > ' +
'</div >';
$("#card_documents > .card-body").append(card);
}
Is my syntax wrong?. Please help. Thanks
You can replace for (var a = 0; a < 2; a++) { "a" } with "a".repeat(2).
More info about repeat() here
Yes, your syntax is wrong. Specifically the way you're trying to use the for loop.
I would suggest building up the string in a variable.
Here is a stripped down version of how you might achieve that.
var card = '<div class="card">';
for (var a = 0; a < 2; a++) {
card += "a";
}
card += '</div>';
$("#card_documents > .card-body").append(card);

apply diffrent css for text separated by comma inside <div>

i am trying to change color for text which are separated by comma(','). i cant use any other tag to separate these. is that possible by jQuery or by css?
<div data-value="ABCD,XYZ" style="padding-left: 12px; padding-right: 12px;">ABCD,XYZ</div>
<div data-value="ABCD,XYZ" style="padding-left: 12px; padding-right: 12px;">cdE,hhhh</div>
Created a fiddle for you
var colorArr = ['red', 'green'];
$( "[data-value='ABCD,XYZ']" ).each ( function(){
var valueArr = $( this ).html().split( "," );
console.log( valueArr );
for (var counter = 0; counter < valueArr.length; counter++ )
{
valueArr[ counter ] = "<span style='color:" + colorArr[ counter ] + "'>" + valueArr[ counter ] + "</span>";
}
console.log( valueArr );
$( this ).html( valueArr.join("") );
} );
Im not sure if you are referring to the innerHTML or the tag's value.. either way. I was not able to test this due to browser issues.
$('div').each(function(){
var textArray = $(this).html().split(',');
var html = '';
for(var i = 0; i < textArray.length; i++) {
html += '<span style="color: #12345' + i + '">' + textArray[i] + '</span>';
}
$(this).html(html);
}
This is what I would do:
$("[data-value]").each(function(){
var words = $(this).text().split(",");
$(this).text("");
for(var i=0; i< words.length; i++){
var r = Math.floor((Math.random() * 255) + 1);
var g = Math.floor((Math.random() * 255) + 1);
var b = Math.floor((Math.random() * 255) + 1);
$(this).append("<span style='color:rgb("+r+","+g+","+b+")'>"+words[i]+ ((i< words.length-1) ? ",":"")+"</span>");
}
});
Here is the JSFiddle demo
The code randomly generates colors and sets a different color for each word.
You can use
:contains() css3 selector
Check this out
$(document).ready(function(){
$('div').each(function(){
var text = $(this).text();
var array = text.split(',');
var html = array[0] + ',<span style="color:red">' + array[1] + '</span>';
$(this).html(html);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-value="ABCD,XYZ" style="padding-left: 12px; padding-right: 12px;">ABCD,XYZ</div>
<div data-value="ABCD,XYZ" style="padding-left: 12px; padding-right: 12px;">cdE,hhhh</div>
Since you are using attr data use .data() to find your elements
$('div').data('value','ABCD,XYZ').each(function(i,vi){
var arrVi = vi.innerText.split(',');
var html = '';
arrVi.forEach(function(vj,j){
html += '<span style="color: green">' + vj + '</span>';
});
vi.innerHTML= html;
})
Change the code to the ways it suits you better.
If you can't change the html code at all you can use :before and :after pseudo selectors.
Split the text by ,.
Set attributes for each of them.
Set content to :before and :after by the attributes
Style those pseudo elements.
This solution will works only with 1 comma separation.
[].forEach.call(document.querySelectorAll('div'), function(item) {
// check if there is a , in the text
if (item.innerText.indexOf(',') > -1) {
var texts = item.innerText.split(',');
item.setAttribute('data-text1', texts[0]);
item.setAttribute('data-text2', texts[1]);
item.innerHTML = ',';
}
});
div:before {
content:attr(data-text1);
color:red;
}
div:after {
content:attr(data-text2);
color:yellow;
}
<div data-value="ABCD,XYZ" style="padding-left: 12px; padding-right: 12px;">ABCD,XYZ</div>
<div data-value="ABCD,XYZ" style="padding-left: 12px; padding-right: 12px;">cdE,hhhh</div>

Adding a <span> to each letter in responsive wordpress theme

I want to create separate backgrounds for each letter in the site-description span within the header on the Wordpress responsive theme.
I have added a function in functions.php
<?php
/**
* Setup Responsive Child Theme Functions
*/
function site_description_spans() {
echo 'Text within header'; // Replace this line with code from `https://stackoverflow.com/questions/17517816/color-every-character-differently
}
add_action( 'responsive_in_header', 'site_description_spans' );
?>
This successfully targets within the header within the responsive theme
But then I tried to add the following code within this function from another Stack Exchange post by replacing the
echo 'text within header' //above
The link to the javascript function on stack exchange is here
Color every character differently
and the relevant code is
$('.site-description').find('span').each(function(){
var $el = $(this),
text = $el.text(),
len = text.length,
newCont = '';
for(var i=0; i<len; i++){
var bgColor= '#'+ (Math.random() * 0xffffff).toString(16).substr(-6);
newCont += '<span style="background:'+bgColor+'">'+ text.charAt(i) +'</span>';
}
$el.html(newCont);
});
And it doesn't seem to work. Would be grateful for any suggestions.
Now i'm not too sure on the outputted HTML but i'm going to take a wild guess, that this is how the HTML is being output:
<span class="site-description">
Text within header
</span>
What you need if the code is to work as expected
<div class="site-description">
<span>
Text within header
</span>
</div>
Option 1 - Change HTML
Change your HTML code so that a span is contained within a div and the function to add the text is within the span
Something like this
<div class="site-description">
<span>
<!-- RUN FUNCTION HERE -->
</span>
</div>
Option 2 - Change jQuery
Change your jQuery function to something like this:
$('.site-description').each(function() {
var $el = $(this),
text = $el.text(),
len = text.length,
newCont = '';
for (var i = 0; i < len; i++) {
var bgColor = '#' + (Math.random() * 0xffffff).toString(16).substr(-6);
newCont += '<span style="background:' + bgColor + '">' + text.charAt(i) + '</span>';
}
$el.html(newCont);
});
Or generally just fix the first part of the query so that it finds the correct class or element.
Ok,
I have tried option 2 and just inserted it in the original function but I am not really sure what I am doing here. I understand what you suggested in option 2 and it looks like that would work, I am just not sure how to add it as a function in functions.php
This is what I have
function site_description_spans() {
$('.site-description').each(function() {
var $el = $(this),
text = $el.text(),
len = text.length,
newCont = '';
for (var i = 0; i < len; i++) {
var bgColor = '#' + (Math.random() * 0xffffff).toString(16).substr(-6);
newCont += '<span style="background:' + bgColor + '">' + text.charAt(i) + '</span>';
}
$el.html(newCont);
});
}
add_action( 'responsive_in_header', 'site_description_spans' );
?>
Trouble is that I get the following error with it
Parse error: syntax error, unexpected '(', expecting T_VARIABLE or '$' in /***/*****/public_html/*****/dev/wp-content/themes/responsive_child/functions.php on line 11

Please help me in this javascript for 'read more' link of post summary

I am using this code on my blogger blog.This is the javascript-
<script type='text/javascript'>
var thumbnail_mode = & quot;
yes & quot;; //yes -with thumbnail, no -no thumbnail
summary_noimg = 430; //summary length when no image
summary_img = 340; //summary length when with image
img_thumb_height = 200;
img_thumb_width = 200;
</script>
<script type='text/javascript'>
//<![CDATA[
function removeHtmlTag(strx, chop) {
if (strx.indexOf("<") != -1) {
var s = strx.split("<");
for (var i = 0; i < s.length; i++) {
if (s[i].indexOf(">") != -1) {
s[i] = s[i].substring(s[i].indexOf(">") + 1, s[i].length);
}
}
strx = s.join("");
}
chop = (chop < strx.length - 1) ? chop : strx.length - 2;
while (strx.charAt(chop - 1) != ' ' && strx.indexOf(' ', chop) != -1) chop++;
strx = strx.substring(0, chop - 1);
return strx + '...';
}
function createSummaryAndThumb(pID) {
var div = document.getElementById(pID);
var imgtag = "";
var img = div.getElementsByTagName("img");
var summ = summary_noimg;
if (thumbnail_mode == "yes") {
if (img.length >= 1) {
imgtag = '<span style="float:left; padding:0px 10px 5px 0px;">
<img src="' + img[0].src + '" width="' + img_thumb_width + 'px" height="' + img_thumb_height + 'px"/>
</span>';
summ = summary_img;
}
}
var summary = imgtag + '<div>' + removeHtmlTag(div.innerHTML, summ) + '</div>';
div.innerHTML = summary;
}
//]]>
</script>
And this is the code i am using in div of post element
<div expr:id='"summary" + data:post.id'>
<data:post.body/>
</div>
<a class='more' expr:href='data:post.url'> read more </a>
<script type='text/javascript'>
createSummaryAndThumb( & quot; summary < data: post.id / > & quot;);
</script>
This is the result:
Twitter is the second most popular social networking site. It is used by celebrities all around world. It is also called a microblogging website... read more
I want read more link just after ' ...' for example-
It is also called a microblogging website... read more
How can i do it, please help me.
Just one solution of many, but give your div prior to the anchor a display:inline; css styling and the anchor will fall to the right of the div content. Either in another included css file, in a style tag, or within the div tag place a style="display:inline".

Categories

Resources