I would like to add a jquery toggle effect on my code which has HTML within my Javascript. Any advice?
GuessGame.prototype.createBoard = function(){
var html = '';
Object.keys(this.cards).forEach(function(key) {
html += '<div class="card" id="' + key + '"';
html += ` style='background-image: url(img/${key}.jpg)'`;
html += '>'
html += '<div class="front" ';
html += 'id="' + key + '">';
html += '</div>';
html += '</div>';
});
// Add all the divs to the HTML
document.getElementById('board').innerHTML = html;
In your example you're not really using the power of jQuery.
Here is a better approach.
GuessGame.prototype.createBoard = function(){
var board = $('#board');
Object.keys(this.cards).forEach(function(key) {
var card = $('<div class="card" id="' + key + '" style="background-image: url(img/${key}.jpg)"><div class="front"></div></div>');
// add onClick Event
card.on('click', function(e) {
card.toggleClass('toggled-class');
});
// append card to board
board.append(card);
});
Related
I have this function that add's to my cart html, and its working fine. But when i add two of the same Item i get an error(only changes color in the first of each same item).
The console.log(changeBackgroundColor); console.log(changeColorText); gets only the first div of each game.
const addToCart = function () {
getJSON('games.json', function (err, data) {
var cartBets = document.getElementById('cart-bets');
if (err === null) {
console.log('Ocorreu um erro' + err);
} else {
let html = '';
regexPrice = data.types[whichLoteriaIsVar].price;
totalPrice += regexPrice;
let newTotalPrice = data.types[whichLoteriaIsVar].price
.toFixed(2)
.replace('.', ',');
html += '<div class="bar-side-cart">';
html += '<div class="side-by-side">';
html +=
'<div class="menu-thrash-save"><i onclick="deleteItemCart(this)" value="' +
data.types[whichLoteriaIsVar].price +
'" class="far fa-trash-alt" src="img/thrash-can.jfif" width=15 alt="Thrash"></i>
</div>';
html +=
'<div data-style="cart-thrash-side-bar-' +
data.types[whichLoteriaIsVar].type +
'" class="bets-backgroundcolor-lotos-container"></div>';
html += '<div class="top-by-top">';
html += '<p class="cart-right-text">' + totalNumbers + '</p>';
html += '<div class="side-by-side">';
html +=
'<div data-style="cart-text-thrash-' +
data.types[whichLoteriaIsVar].type +
'" class="bets-color-lotos-container">' +
data.types[whichLoteriaIsVar].type +
'</div>';
html += '<div class="cart-money">R$ ' + newTotalPrice + '</div>';
html += '</div>';
cartBets.innerHTML += html;
var changeBackgroundColor = document.querySelector(
'[data-style="cart-thrash-side-bar-' +
data.types[whichLoteriaIsVar].type +
'"]'
);
changeBackgroundColor.style.backgroundColor =
data.types[whichLoteriaIsVar].color;
var changeColorText = document.querySelector(
'[data-style="cart-text-thrash-' +
data.types[whichLoteriaIsVar].type +
'"]'
);
changeColorText.style.color = data.types[whichLoteriaIsVar].color;
console.log(changeBackgroundColor);
console.log(changeColorText);
getCartTotal();
}
});
};
document.querySelector() only returns the first matched element. Try using document.querySelectorAll() with a loop:
var changeBackgroundColor = document.querySelectorAll(
'[data-style="cart-thrash-side-bar-' +
data.types[whichLoteriaIsVar].type +
'"]'
);
changeBackgroundColor.forEach(
element => element.style.backgroundColor =
data.types[whichLoteriaIsVar].color
);
Trying to print my htmlString in the .listing div but I'm only getting the last item in the array, yet the console.log loops correctly. what gives?
$.each(json.products, function(index, product) {
// build product block
var htmlString = '<div class="product large-3 columns">';
//open imgwrap
htmlString += '<div class="imgwrap">';
//get img src
htmlString += ' <img class="item_img" src="http://api.example.com/assets/images/' + product.itemCode + '#2x.jpg" />';
// close imgwrap
htmlString += '</div>';
// open textwrap
htmlString += '<div class="textwrap">';
// get productName
htmlString += '<h1 class="product_headline">' + product.productName + '</h1>' ;
// get itemCode
htmlString += '<h4 class="item_id" >' + product.itemCode + '</h4>';
// get description
// get price
// close divs
htmlString += '</div>';
console.log(htmlString);
$('.listing').html(htmlString);
}); //end each
You are overriding the contents of listing in each iteration, instead you need to append the contents.
When you use .html() it will remove the current contents of the element, then replace it with the passed content. To add the new content after the existing one you can use .append()
If you want to clear the listing element, you can do it before the beginning of the loop as shown below
$('.listing').html(''); //clear the listing element if needed
$.each(json.products, function(index, product) {
// build product block
var htmlString = '<div class="product large-3 columns">';
//open imgwrap
htmlString += '<div class="imgwrap">';
//get img src
htmlString += ' <img class="item_img" src="http://api.example.com/assets/images/' + product.itemCode + '#2x.jpg" />';
// close imgwrap
htmlString += '</div>';
// open textwrap
htmlString += '<div class="textwrap">';
// get productName
htmlString += '<h1 class="product_headline">' + product.productName + '</h1>';
// get itemCode
htmlString += '<h4 class="item_id" >' + product.itemCode + '</h4>';
// get description
// get price
// close divs
htmlString += '</div>';
console.log(htmlString);
$('.listing').append(htmlString); //add the current content to existing one
}); //end each
With .html() you're replacing the contents after each loop. Instead, append:
$('.listing').html(htmlString);
becomes:
$('.listing').append( $(htmlString) );
Im editing/creating the following script for my website.
As you can see below I want him to add a <div class="row"> at the start of every row. (Hard to explain).
Then with the var "getal" I want him to END this DIV tag after 4 items in it (4x the foreach loop)
But the way I'm trying to do it with the If loops is not working. Any ideas? (The code is working fine without the <div class="row">, if loops and var getal.
function show_albums (response) {
var getal = 0;
//hide main loader
$('#loading_gallery').hide();
$.each(response.data, function(key, value) {
//create html structure
//rijen teller
if (getal = 0 ) {
var html = '<div class="row">';
$('#albums').append(html);
}
//albums
var html = '' +
'<div class="col-lg-3 col-md-3 col-xs-3 thumb" id="album_' + key + '"> ' +
'<img class="img-thumbnail" id="album_cover_' + key + '" />' +
'<img id="loading_' + key + '" src="images/ajax-loader.gif" />' +
'<h2>' + value.name + '</h2>' +
'<p>' + value.count + ' foto's</p>' +
'</div>';
getal++;
if (getal = 4) {
var html = '</div>';
$('#albums').append(html);
getal = 0;
}
$('#albums').append(html);
}
}
You are using the assignment operator = instead of the comparison operator == in your if statements. Try replacing those.
I have the following .js code but when i test the site, it only displays the wordings as seen in each but no contents. What i want to achieve at the end is to be able to display 5 posts and also add a link at the bottom to display more mosts:
$(document).ready(function(){
url = 'http://hopexxx.com/category/daily-devotion/feed/';
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
error: function(){
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function(data){
var postlist = data.responseData.feed.entries;
var html = '<ul data-role="listview" data-filter="true">';
for (var i = 0; i < 5; i++) {
html += '<li>';
html += '<a href="#">';
html += '<div class="entry">entry.title</div>';
html += '<div class="entry">author</div>';
html += '<div class="entry">publishedDate</div>';
html += '<div class="entry">contentSnippet</div>';
html += '</a>';
html += '</li>';
}
html += '</ul>';
$("#postlist").append(html);
$("#postlist ul[data-role=listview]").listview();
}});
});
If you know that your postlist is not null, and that each entry has properties 'title', 'author', 'publishedDate' and 'contentSnippet' try this:
var postlist = data.responseData.feed.entries;
var html = '<ul data-role="listview" data-filter="true">';
for (var i = 0; i < 5; i++) {
var entry = postlist[i];
html += '<li>';
html += '<a href="#">';
html += '<div class="entry">' + entry.title + '</div>';
html += '<div class="entry">' + entry.author + '</div>';
html += '<div class="entry">' + entry.publishedDate + '</div>';
html += '<div class="entry">' + entry.contentSnippet + '</div>';
html += '</a>';
html += '</li>';
}
html += '</ul>';
$("#postlist").append(html);
try a $.each loop on data.responseData.feed.entries, see here for details
I am currently working with an Image uploader(Source Files). I am having difficulties creating duplicate preview fields. I am creating the preview image form but it is only displaying one thumbnail. How can i get the Js to give me two thumbnails? Here is a LIVE EXAMPLE and further explanation to my source code
This what I initially want to do:
Snippet of JS for creating the preview Image forms(thumbnails)
upLoaderPreviewer.js
<script>
function createImageForm(index) {
var form = '';
form += '<div><table cellspacing="0">';
form += '<tr><td class="label">'
+ '<label for="imageToUpload' + index + '">'
+ $.uploaderPreviewer.messages.imageLabel + ' ' + index + ':</label></td>';
form += '<td class="removeImageButton">'
+ '</td>';
form += '<td class="imageFormFileField">'
// BUG: If the "enctype" attribute is assigned with jQuery, IE crashes
+ '<form enctype="multipart/form-data">'
+ '<input id="imageToUpload' + index + '" type="file" />'
+ '<input type="hidden" name="currentUploadedFilename"'
+ ' class="currentUploadedFilename" /></form>'
+ '</td></tr>';
form += '<tr><td></td><td></td><td>'
+ '<div class="previewImage" style="float:left; margin:10px 10px 10px 0; "><img /></div>'
+ '<button type="button" class="small removeImage"></td></td></tr></table></div>';
return form;
};
</script>
try this:
replace the function 'displayImage' on the uploaderpreviewer.js with this:
function displayImage($previewDiv, imageUrl) {
//New
var yourCustomPreview = $('#custompreview');
var imageFilename = imageUrl.substr(imageUrl.lastIndexOf('/') + 1);
$previewDiv
.removeClass('loading')
.addClass('imageLoaded')
.find('img')
.attr('src', imageUrl)
.show();
$previewDiv
.parents('table:first')
.find('input:hidden.currentUploadedFilename')
.val(imageFilename)
.addClass('imageLoaded');
$previewDiv
.parents('table:first')
.find('button.removeImage')
.show();
//New
yourCustomPreview.prepend('<img src="' + imageUrl + '"/>');
}
and add this where you whant to duplicate the thumb:
<div id="custompreview">
</div>