0

Im trying wrap the image tag and title tag inside the div tag (all are created dynamically) but for some odd reason it says "TypeError: Assignment to constant variable.at Array.forEach"! could someone tell me what am i doing wrong in this code also if its not much, i also want to know if there is a way to add event listener to all these dynamic divs or images of these div! thank you ...

window.onload = function() {
    $.ajax({
            type: "get", 
            dataType: 'jsonp', 
           url:"https://api.themoviedb.org/3/movie/now_playing?api_key=05b5e7574eac47fdf8f2ac12831493c6&language=en-US&page=1", //url to send to 
            contentType: "application/json; charset=utf-8",
            success: function (msg) { 
                 //console.log(msg);

                 msg.results.forEach((e)=>{
    const div = $(`<div id=${e.id}></div>`);
    const title=$(`<p>${e.title}</p>`);
    const img=$(`<img src=https://image.tmdb.org/t/p/w185/${e.backdrop_path}>`);
    //div+='</div>'; // this is what im trying to achieve
    $("#main").append(div);
    $("#main").append(title);
    $("#main").append(img);
});
                       }

});

};
#main
{
  margin-left: 3%;
}


#main>div{
  display: inline-block;
  width: 33%;
  margin-bottom: 10px;
  
}
#main>p
{
  color: red;
  font-size: 150%;

}

#main>img
{
width:10%;

}
 <script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>

<div id="main"></div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • @TylerRoper if i define it as a "let" it prints "object object" and doesnt act as a div – mohamed faizal Jan 28 '19 at 02:18
  • The way in which you declare a variable, be it `var`, `let`, or `const`, has absolutely no effect on its value. Instead, it's likely because of your line `div+=''`, which is trying to combine a string with a jQuery object. `const` will throw an error here, whereas `let` will not, however it's incorrect either way. – Tyler Roper Jan 28 '19 at 02:22

2 Answers2

0

If you want to add the items to the div, you can .append(...) them the same way you did with $("#main").append():

div.append(title).append(img); //append title and image to div
$("#main").append(div);        //append div to main

However, your CSS definitions don't match p or img if they're inside of a div, so you may want to touch those up.

window.onload = function() {
  $.ajax({
    type: "get",
    dataType: 'jsonp',
    url: "https://api.themoviedb.org/3/movie/now_playing?api_key=05b5e7574eac47fdf8f2ac12831493c6&language=en-US&page=1",
    contentType: "application/json; charset=utf-8",
    success: function(msg) {

      msg.results.forEach((e) => {
        let div = $(`<div id=${e.id}></div>`);
        let title = $(`<p>${e.title}</p>`);
        let img = $(`<img src=https://image.tmdb.org/t/p/w185/${e.backdrop_path}>`);

        div.append(title).append(img);
        $("#main").append(div);

      });
    }

  });

};
#main {
  margin-left: 3%;
}

#main>div {
  display: inline-block;
  width: 33%;
  margin-bottom: 10px;
}

#main > div > p {
  color: red;
  font-size: 150%;
}

#main > div > img {
  width: 10%;
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

<div id="main"></div>
Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
  • could you please tell me if there is any way to add a event listener to these dynamically created images ? – mohamed faizal Jan 28 '19 at 02:25
  • That is a separate question, but is [answered here](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements). You need to use event delegation: `$(document).on("click", "#main > div > img", function() { //event here });`, where `"click"` is the event, and `"#main > div > img"` is your desired selector. Declare this event once in your code and it will work for all elements that satisfy the selector, dynamically-created or not. – Tyler Roper Jan 28 '19 at 02:27
  • You *can* use delegation. You don't *need* to use it. You can add a simple handler as each element is being appended to the DOM. Also, you are appending the image as a child of the title instead of appending the image and the title as children of the div. – Scott Marcus Jan 28 '19 at 02:32
  • @ScottMarcus Event delegation is the proper way to do it, so that you only have *one* handler instead of potentially hundreds. Also, I did not mean "need" as in "this is the only way" - seems slightly pedantic. To your point about appending the image to the title, you're incorrect. `.append()` returns the element to which you're appending, so you can chain them together. A simple `Inspect Element` confirms this (and the fact that the CSS `#main > div > img` is styling the images). – Tyler Roper Jan 28 '19 at 02:41
  • You're right about the .append(). But, you are incorrect about delegation. It's not the "proper" way - - it's ***a*** way and that's why I said you *can* use it, but as my answer shows, you don't *need* to use it, as you wrote. Delegation is great for many reasons, but it's not an automatic "go to". – Scott Marcus Jan 28 '19 at 02:43
  • Not sure why you're so dead set on picking apart my semantics here (including *"correct"* which I haven't said). At the end of the day, if OP has 100 movies on his page, he will have 100 event listeners where **1** could have done the job. There are other ways to do it, but you'd have a hard time convincing me that event delegation is not the best approach in this instance. You're making quite the hub-bub about me using the word "need", to such an extent that OP actually removed my accepted answer and chose yours instead lol. – Tyler Roper Jan 28 '19 at 02:49
0

See comments inline:

// Since you are using JQuery, use the document.ready syntax
// which replaces window.onload in your case.
$(function() {
  $.ajax({
     type: "get", 
     dataType: 'jsonp', 
     url:"https://api.themoviedb.org/3/movie/now_playing?api_key=05b5e7574eac47fdf8f2ac12831493c6&language=en-US&page=1", //url to send to 
     contentType: "application/json; charset=utf-8",
     success: function (msg) { 
       msg.results.forEach((e)=>{
        
         // Don't use const if you want to be able to modify the variable later.
         let div = $(`<div id=${e.id}></div>`);
         let title=$(`<p>${e.title}</p>`);
         let img=$(`<img src=https://image.tmdb.org/t/p/w185/${e.backdrop_path}>`);
    
         // Append the title and the img to the new div
         div.append(title);
         div.append(img);
    
         $("#main").append(div); // And then the div to main
        
         // Now that the elements has been made and added to the DOM, you can
         // attach a click event to it easily:
         $(div).on("click", function(){
           // Whatever you need here
           console.clear();
           console.log("You clicked " + e.title);
         });
       });
    }
  });
});
#main { margin-left: 3%; }
#main>div { display: inline-block; width: 33%; margin-bottom: 10px; }
#main > div > p { color: red; font-size: 150%; } /* Your selector was wrong to select the title */
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>
<div id="main"></div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71