I have used jQuery to display images from a JSON file. However the 2 images appear twice when I only want to display one of each.
JSON:
{
"tiles": [
{
"city": "example",
"img" : "example.jpg"
},
{
"city": "example",
"img" : "example.jpg"
}
]
}
HTML:
<div class="tile-image"></div>
<div class="tile-image"></div>
CSS:
.tile-image img {
width: 432px;
height: 192px;
object-fit: cover;
border-radius: 4px;
}
jQuery:
jQuery(document).ready(function ($) {
var jsonURL = "example.json";
$.getJSON(jsonURL, function (json) {
var imgList = "";
$.each(json.tiles, function () {
imgList += '<div><img src= "' + this.img + '"></div>';
});
$('.tile-image').append(imgList);
});
});
I have tried removing the two div containers from my HTML but when I do this all the images disappear. Any suggestions as to why they are appearing twice instead of once would be great.
The issue is because you append the imgList to all .tile-image elements.
To fix this you could instead loop over the .tile-image and append the img from the response data at the matching index, like this:
// mock AJAX response:
var response = {
"tiles": [{
"city": "example",
"img": "example-1.jpg"
}, {
"city": "example",
"img": "example-2.jpg"
}]
}
jQuery(function($) {
// inside the AJAX callback...
// $.getJSON('example.json', function (response) {
$('.tile-image').each(function(i) {
$(this).append('<div><img src= "' + response.tiles[i].img + '"></div>');
});
// });
});
.tile-image img {
width: 432px;
height: 192px;
object-fit: cover;
border-radius: 4px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tile-image"></div>
<div class="tile-image"></div>
Related
My webpage is receiving through AJAX GET requests Arrays with strings, and a Boolean.
The objects within the array are displayed subsequently to shape a chat app, the received array represents messages to display in a chatbox. However, some of the messages are bot's answers, stored as a user message.
Therefore, to recognize such message, I added a Boolean Value (bot=True : This is a bot answer). Such message has to be displayed on the right of the chatbox, when user messages are diplayed on the left. My code is brute forcing the left side of the chatbox, whatever the boolean value.
HTML:
<div id="display" class="chatbox"></div>
CSS:
.chat {
border-top: 1px solid #CCC;
margin-top: 1em;
border-radius: 2px;
color: white;
padding-top: 1em;
padding-bottom: 1em;
display: flex;
flex-direction: column;
}
JS:
<script>
$(document).ready(function() {
function imgMarkup(model) {
if (model.mediasrc) {
return `<img class='imgchat' src=../static/${model.mediasrc}.png/>`
}
return '';
}
setInterval(function() {
$.ajax({
type: 'GET',
url: "/checkview",
success: function go(response) {
console.log(response);
$("#display").empty();
for (var model of response.models_to_return) {
const temp = `
<div class='chat'>
<span class='time-left'>${model.datetime}</span>
<b>${model.user_id}</b>
<p>${model.room}</p>
${imgMarkup(model)}
</div>`;
$("#display").append(temp);
}
},
error: function(response) {
//alert('An error occured')
}
});
}, 1000);
})
</script>
I would like to be able to add a second class to my .chat (css), like class="chat right" depending on the boolean value of the variable 'bot' from the AJAX response.
Use a variable to hold the additional class, and set it conditionally based on model.bot.
$(document).ready(function() {
function imgMarkup(model) {
if (model.mediasrc) {
return `<img class='imgchat' src=../static/${model.mediasrc}.png/>`
}
return '';
}
setInterval(function() {
$.ajax({
type: 'GET',
url: "/checkview",
success: function go(response) {
console.log(response);
$("#display").empty();
for (var model of response.models_to_return) {
let botclass = model.bot ? 'right' : '';
const temp = `
<div class='chat ${botclass}'>
<span class='time-left'>${model.datetime}</span>
<b>${model.user_id}</b>
<p>${model.room}</p>
${imgMarkup(model)}
</div>`;
$("#display").append(temp);
}
},
error: function(response) {
//alert('An error occured')
}
});
}, 1000);
})
I´m using the jQuery UI tooltip plugin.
Now I want to change the <div class="ui-tooltip-content"> in <div class="ui-tooltip-content2"> with jQuery.
I´m using $('.ui-tooltip-content').addClass('ui-tooltip-content2').removeClass('ui-tooltip-content') inside the "each" function but it doesn´t show any effect. I don´t get an error in the console.
I´ve made a JSFiddle. Just inspect the tooltip and you will see that the class hasn´t changed.
Complete code:
$('*[data-id]').tooltip({
tooltipClass: "tooltipitem",
content: '<div class="loading">Laden...</p>',
hide: {
effect: "slide",
delay: "10000"
},
position: {
my: "left+153 top+20",
collision: "flipfit"
},
});
$('*[data-id]').each(function () {
let $tooltip = $(this);
let id = $tooltip.attr("data-id");
ajaxManager.add({
url: "https://xy.eu/datenbank/itemscript.php",
type: "GET",
cache: "true",
data: {
"var": id,
},
success: function (data) {
let $content = $(data);
let title = $content.siblings('[class^=item-titletl]').text()
let icon = $content.siblings('[class^=parent2]').html()
$tooltip.tooltip({
content: function () {
return [data];
},
});
$('.ui-tooltip-content').addClass('ui-tooltip-content2').removeClass('ui-tooltip-content');
$tooltip.attr("title", "=")
$("<img class='icon-small' src='https://xy.eu/images/icons/" + icon + "'/
>" + title + "</>").appendTo($tooltip);
}
});
});
});
The problem is that the tooltip appends when you hover over the element, that's why this code doesn't working, you element was not created yet, at that moment.
$('.ui-tooltip-content').addClass('ui-tooltip-content2').removeClass('ui-tooltip-content');
You can do it by adding this option, this will add additional class to ui-tooltip-content
classes: {
"ui-tooltip-content": "ui-tooltip-content2"
},
The full code will be
$tooltip.tooltip({
classes: {
"ui-tooltip-content": "ui-tooltip-content2"
},
content: function () {
return [data];
},
});
Remove this line:
$('.ui-tooltip-content').addClass('ui-tooltip-content2').removeClass('ui-tooltip-content');
You can check the docs here.
the problem is in your code you are trying to add and remove classes but the element is not present in DOM. I have modified your code
jQuery(document).ready(function ($) {
var ajaxManager = $.manageAjax.create('cacheQueue', {
queue: true,
cacheResponse: true
});
// Tooltip Script
$('*[data-id]').tooltip({
tooltipClass: "tooltipitem",
content: '<div class="loading">Laden...</p>',
hide: {
effect: "slide",
delay: "100000"
},
position: {
my: "left+153 top+20",
collision: "flipfit"
},
});
$('*[data-id]').each(function () {
let $tooltip = $(this);
let id = $tooltip.attr("data-id");
ajaxManager.add({
url: "https://elder-scrolls-online.eu/datenbank/itemscript.php",
type: "GET",
cache: "true",
data: {
"var": id,
},
success: function (data) {
let $content = $(data);
let title = $content.siblings('[class^=item-titletl]').text()
let icon = $content.siblings('[class^=parent2]').html()
$tooltip.tooltip({
content: function () {
return [data];
},
});
setTimeout(AdAndRemoveClass,500);
$tooltip.attr("title", "=")
console.log($tooltip)
$("<img class='icon-small' src='https://www.elder-scrolls-online.eu/images/icons/" + icon + "'/ >" + title + "</>").appendTo($tooltip);
}
});
});
});
function AdAndRemoveClass(){
var tool= $('.ui-tooltip-content');
if(tool.length ==0){
setTimeout(AdAndRemoveClass,500);
}
else{
console.log(tool)
tool.addClass('ui-tooltip-content2');
tool.removeClass('ui-tooltip-content');
}
}
check the working fiddle here
While using introjs.js, I am trying to set the position of a tooltip (.introjs-tooltip) but, if I use the onafterchange event, my code runs, and then the position of the tooltip is set by introjs, and my values for top and left are overwritten. How can I make my change AFTER introjs has done it's calculations for the location of the tooltip?
<div>
<div class="divStep step1">
<span>Nothing much going on here</span>
</div>
<div id="step2" class="divStep step2">
<span>This is step 2</span>
</div>
<div id="step3" class="divStep step3">
<span>This is step 3</span>
</div>
</div>
body {
background-color: #00eeee;
}
.divStep {
display: block;
height: 100px;
width: 400px;
background-color: #fff;
margin: 10px;
padding: 10px;
}
.tt-step2 {
top: 0 !important;
left: 0 !important;
background-color: #ff0000;
}
var myIntro = {
tooltipPosition: 'bottom',
steps: [
{
intro: 'Howdy! This is step 1'
},
{
element: '#step2',
intro: 'This is step 2',
onbeforechange: function(){
console.log('onbeforechange step 2');
$('.introjs-tooltip').addClass('tt-step2');
console.log('has class? ' + $('.introjs-tooltip').hasClass('tt-step2'));
},
onchange: function(){
console.log('onchange step 2');
$('.introjs-tooltip').addClass('tt-step2');
console.log('has class? ' + $('.introjs-tooltip').hasClass('tt-step2'));
},
onafterchange: function(){
console.log('onafterchange step 2');
$('.introjs-tooltip').addClass('tt-step2');
console.log('has class? ' + $('.introjs-tooltip').hasClass('tt-step2'));
}
},
{
element: '#step3',
intro: 'This is step 3'
}
]
}
function launchIntro(){
var intro = introJs();
intro.setOptions(myIntro);
intro
.onbeforechange(function(){
currentStep = this._options.steps[this._currentStep];
if(currentStep.onbeforechange) {
currentStep.onbeforechange();
}
})
.onchange(function(){
currentStep = this._options.steps[this._currentStep];
if(currentStep.onchange) {
currentStep.onchange();
}
})
.onafterchange(function(){
currentStep = this._options.steps[this._currentStep];
if(currentStep.onafterchange) {
currentStep.onafterchange();
}
})
.start();
}
launchIntro();
I came across a similar issue. Currently IntroJS library has an open issue on github.
I had an assignment to heavily customize the elements styles and adjust some behavior.
I managed to handle the situation by using MutationObserver
Here's an example snippet:
const observer = new MutationObserver((mutations) => {
const { target } = mutations[0];
document.querySelector('.introjs-tooltip').style.top = `${
document.querySelector('.introjs-helperLayer').clientHeight
- document.querySelector('.introjs-tooltip').clientHeight - 10}px`;
return null; });
observer.observe(
document.querySelector('.introjs-tooltip'),
{ attributes: true, attributeOldValue: true, attributeFilter: ['style'] },
);
this code works just fine, but the second input field does not show images appearing with the text suggestions. I would appreciate if someone could take a look and let me know what needs to be changed in the js for it to work.
Example queries: clinton, bush
you can see the script here http://predcast.com/include/autoc/jqui/test2.php
<!DOCTYPE html>
<html>
<head>
<title>jQuery UI Autocomplete: Custom HTML in Dropdown</title>
<link href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.min.css" rel="stylesheet">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<style>
.loading {
display: none;
width: 16px;
height: 16px;
background-image: url(/img/loading.gif);
vertical-align: text-bottom;
}
#autocomplete.ui-autocomplete-loading ~ .loading {
display: inline-block;
}
.ui-menu-item {
padding:1px;
margin:1px;
}
.ac-m {
height:block;
overflow:auto;
padding:2px 2px 2px 2px;
}
.ac-img {
max-width:30px;
float:left;
margin:2px 2px 2px 2px;
}
.ac-title {
margin:1px;
font-size:14px;
}
.ui-autocomplete {
margin:1px;
}
</style>
</head>
<body>
<form action="http://www.test.com/">
<input class="autocomplete" type="text" placeholder="Option 1" name="e1">
<input class="autocomplete" type="text" placeholder="Option 2" name="e2">
<span class="loading"></span>
</form>
<script>
/*
* jQuery UI Autocomplete: Custom HTML in Dropdown
* http://salman-w.blogspot.com/2013/12/jquery-ui-autocomplete-examples.html
*/
$(function () {
$('.autocomplete').autocomplete({
delay: 500,
minLength: 3,
source: function (request, response) {
$.getJSON("http://predcast.com/include/autoc/jqui/jsond.php", {
q: request.term,
}, function (data) {
var array = data.error ? [] : $.map(data.movies, function (m) {
return {
label: m.title,
year: m.year,
img: m.img,
};
});
response(array);
});
},
focus: function (event, ui) {
event.preventDefault();
},
}).data("ui-autocomplete")._renderItem = function (ul, item) {
var $a = $("<div class='ac-m'></div>");
if (item.img) {
$("<span></span>").addClass(item.icon).appendTo($a).append("<img src='" + item.img + "' border='0' class='ac-img' />");
}
$("<span class='ac-title'></span>").text(item.label).appendTo($a);
return $("<li></li>").append($a).appendTo(ul);
};
});
</script>
</body>
</html>
The problem is related to the way you are defining the _renderItem extension point.
In your code, you are redefining the jquery-ui autocomplete _renderItem function only for your first widget instance, so the _renderItem for your second autocomplete instance is the default one defined in the jquery-ui code.
You are initializating the autocomplete for your 2 inputs with this $('.autocomplete').autocomplete({ ...}) then you get the first widget instance with this instruction .data("ui-autocomplete") and then redefine the _renderItem function for this instance only.
You can define it for all your instances like this:
// Create your widget instances
$('.autocomplete').autocomplete({
delay: 500,
minLength: 3,
source: function (request, response) {
$.getJSON("http://predcast.com/include/autoc/jqui/jsond.php", {
q: request.term,
}, function (data) {
var array = data.error ? [] : $.map(data.movies, function (m) {
return {
label: m.title,
year: m.year,
img: m.img,
};
});
response(array);
});
},
focus: function (event, ui) {
event.preventDefault();
}
});
// Then redefine the _renderItem for each instance
$('.autocomplete').each(function() {
$(this).data('ui-autocomplete')._renderItem = function (ul, item) {
var $a = $("<div class='ac-m'></div>");
if (item.img) {
$("<span></span>").addClass(item.icon).appendTo($a).append("<img src='" + item.img + "' border='0' class='ac-img' />");
}
$("<span class='ac-title'></span>").text(item.label).appendTo($a);
return $("<li></li>").append($a).appendTo(ul);
};
});
Recently I was able to load javascript in webbrowser before downloading source with this code:
WebBrowser1.Document.Window.DomWindow.execscript("text/JavaScript")
Dim MSDNpage2 As String = WebBrowser1.Document.Body.InnerHtml
My.Computer.FileSystem.WriteAllText("e:\msdn2.txt", MSDNpage2, True)
RichTextBox6.Text = MSDNpage2
Unfortunately, the first line causes a browser error. The following code:
WebBrowser1.ScriptErrorsSuppressed = True
I turn off the notifications, but in this case, the source does not link one I care about. Therefore I ask for your help in solving this problem. I thought that automatic clicking on the 'no' could help, but I could not locate the process responsible for displaying a message.
I don't known how to set attributes, when i've got no error, then code is looks like this:
<DIV id=serialInfoBox>
<DIV class=l>
<DIV class=progressBar>
<DIV class=o>
<DIV style="WIDTH: 0px" class=i></DIV></DIV></DIV><HGROUP>
<H2>SGU Stargate Universe</H2></HGROUP></DIV>
<DIV class=r><IMG src="/static/serials/stargate-universe_small.jpg"> </DIV></DIV>
<DIV id=player>
<DIV id=player_2 hash="wZlV90mq4I3LgyGB6WGIgyKJvMzHhS2EvAGqhWmI25JIRMyrXIUnjAmAeIKJZqQJcIGBV1HInuKLuS2LnS1ZHWTMDqGrBk0FF9FAPSxMvuSJnAxLjZxHXy1IdSzEiSHJ1W1M" jQuery110007841996969566763="5"></DIV>
<DIV class=clearfix></DIV></DIV></DIV>
<DIV id=underPlayer><A class=l href="odcinek,stargate-universe,lost,s01e15.html">poprzedni odcinek</A> <A class=c watched="0" jQuery110007841996969566763="19">zaznacz jako obejrzane</A> <A class=r href="odcinek,stargate-universe,pain,s01e17.html">następny odcinek</A> </DIV>
<SCRIPT type=text/javascript>
$(document).ready(function() {
$('#langs li').click(function(e) {
e.preventDefault();
$('#players li').hide();
$('#players li.'+$(this).attr('id')).show();
$('#langs li').removeClass('active');
$(this).addClass('active');
});
$('#player_2').click(function(e) {
$.post("getVideo.html", {hash: $(this).attr('hash')}, function(data) {
$('#player').css('background','#000').css('text-align','center');
$('#player').html(data);
$('html, body').animate({
scrollTop: $("#player").offset().top-27
}, 1000);
});
});
$('#players a.switcher').click(function(e) {
e.preventDefault();
$.post("getVideo.html", {hash: $(this).parent().attr('hash')}, function(data) {
$('#player').html(data);
$('html, body').animate({
scrollTop: $("#player").offset().top-27
}, 1000);
});
});
$(document).on('click','a.tup',function(e) {
e.preventDefault();
var c_id = $(this).parent().attr('cid');
$.post("commentVote.html",{cid: c_id, mode: "up"}, function(data) {
if (data >= 0) {
$('#cid'+c_id+' span').removeClass('red').removeClass('green').addClass('green');
data = '+'+data;
} else {
$('#cid'+c_id+' span').removeClass('red').removeClass('green').addClass('red');
}
$('#cid'+c_id+' span').html(data);
$('#cid'+c_id+' .tup').remove();
$('#cid'+c_id+' .tdown').remove();
}) ;
});
$(document).on('click','a.tdown',function(e) {
e.preventDefault();
var c_id = $(this).parent().attr('cid');
$.post("commentVote.html",{cid: c_id, mode: "down"}, function(data) {
if (data >= 0) {
$('#cid'+c_id+' span').removeClass('red').removeClass('green').addClass('green');
data = '+'+data;
} else {
$('#cid'+c_id+' span').removeClass('red').removeClass('green').addClass('red');
}
$('#cid'+c_id+' span').html(data);
$('#cid'+c_id+' .tup').remove();
$('#cid'+c_id+' .tdown').remove();
}) ;
});
$('#underPlayer .c').bind('click', function() {
var el = $(this);
if ($(this).attr('watched') == 0) {
$.ajax({type: "POST", url: "/reports,seen.html",timeout: 10000,data: "user=1075505&ep=38361", success: function(data) {
if (data == 1) {
el.html('oznacz jako nieobejrzane').attr('watched','1');
}
}
});
} else {
$.ajax({type: "POST", url: "/reports,seen.html",timeout: 10000,data: "user=1075505&rem=1&ep=38361", success: function(data) {
if (data == 1) {
el.html('zaznacz jako obejrzane').attr('watched','0');
}
}
});
}
return false;
});
})
</SCRIPT>
and there is no link I need, but when there is my link, then i've got an error and code looks like this:
<DIV id=serialInfoBox>
<DIV class=l>
<DIV class=progressBar>
<DIV class=o>
<DIV style="WIDTH: 0px" class=i></DIV></DIV></DIV><HGROUP>
<H2>SGU Stargate Universe</H2></HGROUP></DIV>
<DIV class=r><IMG src="/static/serials/stargate-universe_small.jpg"> </DIV></DIV>
<DIV style="TEXT-ALIGN: center; BACKGROUND: #000" id=player>
<DIV style="POSITION: relative; WIDTH: 750px">
<DIV style="Z-INDEX: 0; TEXT-ALIGN: center; WIDTH: 750px; BACKGROUND: #000; COLOR: #fff">
<DIV class=embed>
<DIV style="Z-INDEX: 0; POSITION: relative; WIDTH: 750px; HEIGHT: 429px; CLEAR: both"><SPAN id=aeceedb4c2667cf66b0cfe9780811fa6></SPAN></DIV>
<SCRIPT type=text/javascript src="http://premium.iitv.info/static/player/flowplayer-3.2.11.min.js"></SCRIPT>
<SCRIPT type=text/javascript>
$(document).ready( function(){
$f("aeceedb4c2667cf66b0cfe9780811fa6", "http://premium.iitv.info/static/player/flowplayer.commercial-3.2.15.swf", {
key: '#$3f90d28e7547ada6c98',
clip: {
here is url: ---> url: 'http://stream.streamo.tv/?scode=wZvoQAIH41HF5MxJiH2MAg0YeVKAFATnLMTGluyIl4HFeZyGCAUFhqGM5DREz9JnlM2MUAJEmq3HlSIBVgxq6OKqeRxHDATERSUZTAmqkHGn5cJA1yyZgA0pKcHDdAmMkRGZ2A2pfWKqeSKD4NUIQkRqVWwEIcRrLWmEKIaJbERnDgPFcW3A2RwAj52F6MUIgMyADImXjfvq2EKoMAJGxywD0y0Az50HeLmIy1zM0WTA19FBgWTIBc0FWWTAUAwrCuaEASKIiHQplWwMwMxZm9HZeO1FGMSHMSyELEwZaSRqXSHMjWmX6W2AUOUG2I2DmM0YU9RqjgFAiS0XLcJBDcJBQEQnLcJD142IaM0AL50nSOQJkkxEBSHrBMQBIOmM2qaqGgxo5SzJdAIpjymZ5bKLlyxrDuSokNyZ4ExZPqIJkVwpyqSZbMwZxITEjVIFyqSZIMaMPuUIeSxF5RSHzEQGIyTnIA3o2LwIJ1ToPE1DFyTpUqRqiHHpuSTF0RypBqmpacaG',
provider: 'lighttpd',
scaling: 'fit',
backgroundGradient: 'none',
autoPlay: false,
autoBuffering: false
},
canvas: {
backgroundColor:'#000',
backgroundGradient: 'none'
},
plugins: {
lighttpd: {
url: 'flowplayer.pseudostreaming-3.2.11.swf',
queryString: escape('?start=${start}')
},
controls: {
url: 'flowplayer.controls-3.2.14.swf',
autoHide: 'always'
}
}
});
});
</SCRIPT>