Stop image from caching in jQuery - javascript

I am trying to complete the random quote generator on FreeCodeCamp. I pretty much have it but i decided i wanted to go one step further and change the background image with the button as well. I believe the background img is being cached from the very first call where the background img is originally set. Therefor every time i click the button the browser is essentially reloading the cached img instead of revisiting the site and pulling a new img.
The source i am using is just a site that returns a different image every visit.
I have tried adding a time stamp to the end of the url and the site just throws a invalid address image at me.
<html>
<head>
</head>
<body>
<div class="container-fluid" id="mainDiv">
<div class = "row text-center">
<div class = "col-xs-12 well" id = "quote">
The quote will go here
</div>
</div>
<div class = "row text-center">
<div class = "col-xs-12">
<button id = "getQuote" class = "btn btn-primary">
Get Quote
</button>
</div>
</div>
</div>
</body>
</html>
body{
background-image: ;
}
#mainDiv{
margin: 0 auto;
max-width: 400px;
margin-top: 200px;
}
$(document).ready(function(){
$('body').css('background-image', 'url("https://source.unsplash.com/random")');
$.getJSON("http://quotes.stormconsultancy.co.uk/random.json", function(json){
$("#quote").html('"' +json.quote + '"<br> - ' + json.author);
});
$("#getQuote").on("click", function(){
$('body').css('background-image', 'url("https://source.unsplash.com/random")');
$.getJSON("http://quotes.stormconsultancy.co.uk/random.json", function(json){
$("#quote").html('"' +json.quote + '"<br> - ' + json.author);
});
});
});

Timestamp won't work because it is a 302 redirect, and the client-side script cannot intercept the 302 redirect, it is resolved automatically and you cannot do anything about that. You can read 302 headers on the server side though. You can try getting the image in your server, have it resolve the 302 and respond with the correct url.
If you are using the API you can try using ajax:
$.ajax({
url: "https://api.unsplash.com/photos/random?client_id=32d223323",
cache: false,
success: function(result){
$('body').css('background-image', 'url("' + result.urls.full + '")');
}
});

Related

FCC / Local Weather App / JSON information not displaying info from the OpenWeather API

I am doing the freeCodeCamp Local Weather App Zipline Challenge, and got to the part where I have extracted my location using an IP-Location API, and am supposed to use the location with the Open Weather API to get information about the local weather.
I've done this successfully and opening the JSON links in a new tab in my Browser(Chrome) displays the JSON with all the objects/arrays/info I need/etc.
However, were I to try and log this info to the console or change an html element's contents with specific information from the callback info, I get nothing. Not even any errors.
I did some research and tried to use http instead of https on my codepen, but that didn't solve the problem. I also tried going through some Youtube tutorials, but nobody else encountered the issue.
I have included code snippets with all of my code from the codepen(NOTE: I removed the api key for the local weather app)
Here are some useful links:
1. The challenge info itself: https://www.freecodecamp.com/challenges/show-the-local-weather
2.The IP API I used to get my location: http://ip-api.com/
3.The Open Weather API: https://openweathermap.org/current#geo
EDIT: To make my question more clear: Why does the info I get from the API not display in the HTML elements specified in the jQuery function?
$(document).ready( function() {
var city;
var countryCode;
$.getJSON("http://ip-api.com/json",function(data2){
city = data2.city;
countryCode = data2.countryCode;
var api = "api.openweathermap.org/data/2.5/weather?q="+city+","+countryCode+"&APPID=MYKEYGOESHERE";
$.getJSON(api, function(data3){
$("cityName").html(data3.city);
$("temperature").html(data3.temp);
$("weather").html(data3.weather[0].description);
});
});
});
body{
color:#FFF;
background-color: #f4495d;
}
.mainContainer{
margin:7% auto;
background-color: #ce2336;
width:50%;
}
h2{
text-align:center;
font-size: 180%;
}
p{
text-align:center;
font-size: 150%;
}
<div class="mainContainer">
<h2>The Local Weather APP</h2>
<div class="coordinates">
<p id="data">something something</p>
</div>
<div class="one-Third">
<p id="cityName">YourCity</p>
</div>
<div class="one-Third">
<p id="temperature">TheTemperature</p>
</div>
<div class="one-Third">
<p id="weather">TheWeather</p>
</div>
<img src="#">
</div>
okay based on the comment, you need to fill the html that you are creating, to do this, you have to put "#" character in order to fill a specific element, so your code should be
$(document).ready( function() {
var city;
var countryCode;
$.getJSON("http://ip-api.com/json",function(data2){
city = data2.city;
countryCode = data2.countryCode;
var api = "api.openweathermap.org/data/2.5/weather?q="+city+","+countryCode+"&APPID=MYKEYGOESHERE";
$.getJSON(api, function(data3){
$("#cityName").text(data3.city);
$("#temperature").text(data3.temp);
$("#weather").text(data3.weather[0].description);
});
});
});

continue with same Show and hide divs when we change page

I work with a function in my main page. All works fine, I just want to know how to use the function :
localStorage.setItem("language", selectedLanguage);
currentlanguage= localStorage.getItem("language");
My goal is to keep the select language in a page when i click on a link and go in another page.
For example id="en" is the language by default, but if I want to use id="fr" in my main page, and click on link who will send me in another page. I will come back to id="en". So how can I use localStorage to keep the same language ?
Here is the jsfiddle of the function that I use:
https://jsfiddle.net/kodjoe/chvw181j/
HERE IS MY HTML CODE
<a class="button" id="en">EN</a>
<a class="button" id="fr">FR</a>
<a class="button" id="de">DE</a>
<div class="lan en">1</div>
<div class="lan fr">2</div>
<div class="lan de">3</div>
<div class="lan en">4</div>
<div class="lan fr">5</div>
<div class="lan de">6</div>
HERE IS MY JS
$(document).ready(function() {
$('.lan').hide();
$('.en').show();
});
$('.button').click(function(event) {
$('.lan').hide();
var selectedLanguage = $(this).attr('id');
var setActiveLanguage = "." + selectedLanguage;
$(setActiveLanguage).show();
localStorage.setItem("language", selectedLanguage);
currentlanguage= localStorage.getItem("language");
});
HERE IS MY CSS
.button { cursor:pointer; padding: 0px 30px; }
localStorage.setItem("language", selectedLanguage);
currentlanguage= localStorage.getItem("language");
You could use SessionStorage to save your data (like selected language). Then expend your functions with if-clauses to set the right show/hide-status.
You could use localStorage, but I would just put the code in a file where you'd like to include any global scripts, since you will or already do have other scripts that are applicable to the application as a whole. Then link the file in your head (you'd likely be using an include of some sort for your header content).
<script src="js/globalScripts.js"></script>
//globalScripts.js
$(document).ready(function() {
$('.lan').hide();
$('.en').show();
});
$('.button').click(function(event) {
$('.lan').hide();
var selectedLanguage = $(this).attr('id');
var setActiveLanguage = "." + selectedLanguage;
$(setActiveLanguage).show();
});

Basic Image Viewer with javaScript

I am new with JavaScript and I am trying to learn by coding. I want to make a basic image viewer with a "next" and a "previous" that you can click to move forwards and back through a gallery of ten pictures. So I have my html, my css and my javaScript files and 10 random pictures to try it out.
The files are pretty straight forward:
HTML:
<body>
<div id="wrap">
<div class="firstColumn">
<p>PHOTOGRAPHY</p>
<div class="firstColumnSub">
<p class="photo">SOME TITLE</p>
</div>
</div>
<div class="back">
<p>BACK</p>
</div>
<div id="container">
<div id="controllers">
<div class="buttons" id="previous">
<p onclick="change(-1);">PREVIOUS</p>
</div>
<div class="buttons" id="next">
<p onclick="change(1);">NEXT</p>
</div>
</div>
<div><img height="100%" id="front" src="Image1.jpg"></div>
<div>
<p id="footer">Footer</p>
</div>
</div>
</div>
</body>
Just a few divs with the image in the center and a previous and a next clickable tags. This is what it loos like:
The JavaScript file contains a function that loads the different pitures and -and this is my problem- centers them in the middle of the page by grabbing their width and updating the css:
JavaScript:
window.onload = function setUp() {
var b = document.getElementById("front").width;
document.getElementById("container").style.width = b + "px"
}
var imageCount = 1;
function change(x) {
imageCount = imageCount + x;
var image = document.getElementById('front');
var str1 = "Image";
var str2 = imageCount;
var str3 = ".jpg"
var sum = str1.concat(str2, str3);
image.src = sum;
var a = document.getElementById("front").width;
document.getElementById("container").style.width = a + "px"
}
I an not posting the css unless required, but you get the idea.
As you press "next" or "previous", you are supposed to get this result:
etc... but instead I get all sort of random displays:
And here is the thing that is puzzling me: if you keep clicking "back" and "next", the same pictures appear OK the second time round, so it is working but not immediately. Any help appreciated!
Thanks, P.
This is most likely a CSS positioning issue. The following CSS may do the job for you. If you need further help, then I suggest that you reconsider posting your CSS to get help.
#container #front
{
position: relative;
/* width: 0px; */ /* set via JS for each element in this use case */
left: 0;
right: 0;
margin: 0 auto;
}
Here is a popular Q & A on this subject which contains a lot of resources.

jQuery doesn't work in a dynamic content

I have a problem with my web application. I've created a tchat in Ajax and I want it to be loaded when I click on a button. It works, but the dynamic data loaded doesn't support jQuery.
When I click on the button, I dynamically change the content of a div, initially empty. But on this finder (which open) I have a link which should load smileys simply in changing the height of the div, which is initially at 0 px.
I've done tests, and when I click on the button, the height is good changed, but nothing appear on the screen.
Here is a screenshot of my chat:
When I click on the smiley, I should see that:
But nothing happened.
Here is the code that works fine because the height is changed (I've tested it) :
var elm = window.document.getElementById('myCGU_Appear-1');
if (elm.style.height == "0px") {
elm.style.height = "100px";
elm.style.overflow = "auto";
window.document.getElementById('appear_emoticon-1').src = "/assets/images/emoticons/my_small_emoticons_000.png";
} else {
elm.style.height = "0px";
window.document.getElementById('appear_emoticon-1').src = "/assets/images/emoticons/my_small_emoticons_01.png";
}
I think I've done a mistake somewhere because yesterday the code worked fine...
Here is the code that load the tchat :
$.ajax({
url:"/scripts/ajax/load_tchat.php",
type: "POST",
data: "method_call=open",
dataType: "json",
success: function(data){
console.log(data);
if(data.tchat_operation == 'open') {
// load datas
$("#frameChat").html(data.tchat_content);
// open the tchat
frameChat.classList.remove("Espace-Chat-Ferme");
frameChat.classList.add("Espace-Chat");
}
},
error: function(resultat, statut, erreur){
console.log(resultat);
console.log(erreur);
}
});
And here is the JSON code that is send to me and that I've on my div :
> this.tchat_content
< "
[...]
<div style=\"position: absolute; bottom: 5px; width:280px; class=\"myBackgroundGreyLight\">
<div class=\"section group\">
<div class=\"col span_1_of_1\"><div id=\"myCGU_Appear-1\" name=\"myCGU_Appear-1\" style=\"height:0px;margin-bottom:2%;-webkit-transition:all 0.2s ease-in;transition: 0.5s ease-in-out;overflow: hidden;display:block;\" class=\"myBackgroundGreyLight\">All emoticons</div>
<a href=\"#\" onclick=\"My_CGU_Appear2(-1,5000)\" class= \"button scrolly\" >
<img id=\"appear_emoticon-1\" src=\"/assets/images/emoticons/my_small_emoticons_01.png\" width=\"6%\">
</a><div class=\"fileUpload\">
<input type=\"file\" accept=\"image/x-png, image/gif, image/jpeg, image/jpg\" id=\"imgInp-1\" />
</div>
<div>
<a href=\"#ouvre_photo\" onclick=\"AddImageInInput2(this,-1);\">
<img id=\"blah-1\" src=\"\" alt=\"\" />
</a>
</div><div contentEditable=\"true\" class=\"contact_message\" id=\"txt_comments-1\" onkeyup=\"ia_content_analysis(-1, event,2);\" style=\"background-color:white;max-height:125px;overflow-y:auto;overflow-x:hidden;min-height: 50px;\"></div>
<div id=\"test-1\" style=\"float:right;\">
<h4> </h4>
</div>
<div id=\"callback_-1\" style=\"font-size:11px;margin-top:10px;\"></div>
<div style=\"clear:both; display:block; height:10px;\"></div>
<div style=\"display:inline-block;width:100%;\">
<a style=\"display:inline-block;background-color:#bf0e07;float:right;border-radius:4px;padding:5px;cursor:pointer;width:50px;text-align:center;font-size:12px;color:white;\" rel=\"-1\" class=\"publish_message\">Publier</a>
</div>
</div>
</div>
</div>
<script src=\"/assets/javascript/jquery.min.js\"></script>
<script src=\"/assets/javascript/My_JSFunctions.js\"></script>
<script src=\"/assets/javascript/ajax.js\"></script>"
Thanks if you can help me or show me the right way :)
You haven't set any event handler on your emoticon-button. After loading HTML data via ajax you have to reinitialize all your event handlers previously set on your elements if you had set them via ID. So instead of reinitializing all the time you could try:
$(document).on('click', '#yourButtonId', function() { /* my logic */ });
instead of assigning the event handler directly on the dynamic content. I hope I got you right. Else providing a JSFiddle would help.

Invalid flag to regex error on button click in CodeIgniter

I have a view in which a quiz is displayed using an external js file. When the quiz is completed, I am appending some new html to the screen, including a new button that is suppose to, upon being clicked, send the user to the practiceTask function of my Main controller. However, when it is clicked I get the error:
Uncaught SyntaxError: Invalid flags supplied to RegExp constructor 'practiceTask'
Because the code is in .js file, I can't use site_url or base_url, as far as I know. Is this the correct way to do this?
Relevant JS:
$('#imageLocation').attr("src", "");
var html = '<div class="instruction_block"><p class="instruction_text" style="text-align: center; margin-top: 0">You have completed the ' + text + ' test</p><div class="button_placement" style="margin-top: 300px;"><input class="rounded" style="position: absolute; bottom: 0; right: 0; width: 250px;"" type="button" value="Continue to the next task" onClick="/main/practiceTask/3"></div>';
$('#final_message').append(html);
Main Controller function:
public function practiceTask($task_id){
$this->load->model('Main_model');
echo ($task_id);
$json_key = $this->Main_model->getKey($task_id);
$json_key = json_decode($json_key, true);
shuffle($json_key);
$data['test_key'] = $json_key;
$data['task_id'] = $task_id;
$this->load->view('practice_test_view', $data);
}
Any help would be much appreciated!
If you want to get a value into a JS page, you can put it into a hidden input and parse with JS on the page load so that it is available for you to use.
The problem you might be having is with your onclick
onClick="/main/practiceTask/3"
do this with jQuery
var html = '<div class="instruction_block"><p class="instruction_text" style="text-align: center; margin-top: 0">You have completed the ' + text + ' test</p><div class="button_placement" style="margin-top: 300px;"><input class="rounded" style="position: absolute; bottom: 0; right: 0; width: 250px;"" type="button" value="Continue to the next task" data-url="/main/practiceTask/3"></div>';
$(document).on('click', '.button_placement input', function(e){
e.preventDefault();
window.top.location = $(this).data('url');
});
This way it creates an event that will trigger whenever you click on the button. It will read the data-url value and redirect you to that page.
Good luck ;)

Categories