0

i wanted to create a sliding image gallery in a div. To get the images and the description i make a get request on an api. The returned json is as expected and until that, the code works.

I have found this sliding gallery on W3Ccourses https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_slideshow_auto and i wanted to use it with my data.

I get these 2 errors:

  • Unable to get property 'style' of undefined or null reference Here is the code

  • 'require' is not defined

i have tried with require.js but it didn't work. I tried to create my div even with document.createElement and then .appendChild but it didn't work. I don't think the issue is in creating the html element. Thanks for replying

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {box-sizing: border-box;}
body {font-family: Verdana, sans-serif;}
.mySlides {display: none;}
img {vertical-align: middle;}

/* Slideshow container */
.slideshow-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
}

/* Caption text */
.text {
  color: #f2f2f2;
  font-size: 15px;
  padding: 8px 12px;
  position: absolute;
  bottom: 8px;
  width: 100%;
  text-align: center;
}

/* Number text (1/3 etc) */
.numbertext {
  color: #f2f2f2;
  font-size: 12px;
  padding: 8px 12px;
  position: absolute;
  top: 0;
}

/* The dots/bullets/indicators */
.dot {
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}

.active {
  background-color: #717171;
}

/* Fading animation */
.fade {
  -webkit-animation-name: fade;
  -webkit-animation-duration: 1.5s;
  animation-name: fade;
  animation-duration: 1.5s;
}

@-webkit-keyframes fade {
  from {opacity: .4}
  to {opacity: 1}
}

@keyframes fade {
  from {opacity: .4}
  to {opacity: 1}
}

/* On smaller screens, decrease text size */
@media only screen and (max-width: 300px) {
  .text {font-size: 11px}
}
</style>
</head>
<!-- ####################################################### -->
<body>
<div class="slideshow-container">
<!-- ### want to get this kind of div , but with my data ###
<div class="mySlides fade">
  <div class="numbertext">1 / 3</div>
  <img src="img_nature_wide.jpg" style="width:100%">
  <div class="text">Caption Text</div>
</div>  -->

<script type="text/javascript">

url  = 'http://www.myUrl.com';

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var httpReq = new XMLHttpRequest();
httpReq.open("GET" , url , false);
httpReq.send(null);
var jsonObj = JSON.parse(httpReq.responseText);
var description = jsonObj[i].description

for ( i = 0 ; i < 9 ; i++) {
document.writeln('<div class=\"mySlides fade\">');
document.writeln('<div class = \"numbertext\">' + i + '/9</div>');
document.writeln('<a href = \"https://www.that-product.com\"><img src=\"' + jsonObj[i].url_image + '\" style="width :100%"></a>');
document.writeln('<div class=\"text\">' + description + '</div>');
}
</script>
</div>

<div style="text-align:center">
  <span class="dot"></span>
  <span class="dot"></span>
  <span class="dot"></span>
  <span class="dot"></span>
  <span class="dot"></span>
  <span class="dot"></span>
  <span class="dot"></span>
  <span class="dot"></span>
  <span class="dot"></span>
</div>

<script>
var slideIndex = 0;
showSlides();

function showSlides() {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("dot");
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slideIndex++;
  if (slideIndex > slides.length) {slideIndex = 1}
  for (i = 0; i < dots.length; i++) {
    dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex-1].style.display = "block";
  dots[slideIndex-1].className += " active";
  setTimeout(showSlides, 2000); // Change image every 2 seconds
}
</script>
</body>
</html>
charlietfl
  • 170,828
  • 13
  • 121
  • 150
federico
  • 3
  • 1
  • For the `require is not defined` error, it looks like you are trying to use the Node.js [require function](https://nodejs.org/api/modules.html#modules_require_id) in your browser, which won't work. See this answer: https://stackoverflow.com/a/9901097/8135076 – ty2k Jul 19 '19 at 16:52
  • For the `'style' of undefined` error, your `slides` variable is undefined because the function that appends your `
    `s with the class `mySlides` is failing due to the `require is not defined` error.
    – ty2k Jul 19 '19 at 16:58
  • I see a bunch of problems in your code: 1. You have no validating of the response of your ajax call, 2. Has every Ajax call really 9 entries? 3. Why have you mask the " insight the document-writeln strings? 4. the showSlides function will be called recursive as a callback insight the setTimeout – Thomas Deutschländer Jul 19 '19 at 17:02

2 Answers2

0

I checked you code and I notice three things,

  • You don't need this line var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; you don't need to require it here as the XMLHttpRequest is part of the windows object.

  • Your usage of the xmlhttprequest method is wrong see correct implementation below.

var url  = 'http://www.myUrl.com';
var httpReq = new XMLHttpRequest();

httpReq.open("GET" , url);
httpReq.send(null);

var jsonObj, description;
httpReq.onload = function() {
  if (httpReq.status == 200) { // analyze HTTP status of the response
    var jsonObj = JSON.parse(httpReq.responseText);
    var description = jsonObj[i].description // e.g. 404: Not Found
    for ( i = 0 ; i < 9 ; i++) {
      document.writeln('<div class=\"mySlides fade\">');
      document.writeln('<div class = \"numbertext\">' + i + '/9</div>');
      document.writeln('<a href = \"https://www.that-product.com\"><img src=\"' + jsonObj[i].url_image + '\" style="width :100%"></a>');
      document.writeln('<div class=\"text\">' + description + '</div>');
    }
    var slideIndex = 0;
    showSlides();
  } else { // show the result
    alert(`Error: httpReq.status`); // responseText is the server
  }
};
  • You will get a CORS error if you are not running this from the same origin as http://www.myUrl.com

Hope this helps.

0

You can use ajax request to retrieve your json data, then loop each object while appending a mySlides div

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script>
<script>
$(document).ready(function(){
    $.getJSON("https://jsonplaceholder.typicode.com/todos/1", function(result){
      $.each(result, function(i, field){
        $("div.slideshow-container").append(`<div class="mySlides fade"><div class="numbertext">1 / 3</div><img src="${field.url}" style="width:100%"><div class="text">${field.caption}</div></div>`);
      });
    });
 showSlides();
});

</script>
CharukaHS
  • 561
  • 1
  • 5
  • 16