Display random content from object

111

I don't really understand whout should be random, so I started with a random project display in the container.

  1. Created an array of the project objects

  2. Created a function that creates the HTML to be appended to the DOM container

  3. Created a function that sets a random number from 0 to (project) array length, and appends the HTML to the DOM container

  4. Decoupled the event from the DOM by using HTML.addEventListener(), and placed the random function there (on click event)

Now, if you press the button, a random project is selected from the array, and it is displayed in the container

const arr = [{
    name: "Site 1",
    url: "https://www.google.ro/",
    description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
    site_image: ["https://adpconstruct.ro/wp-content/uploads/2019/07/poza52.jpg", "https://adpconstruct.ro/wp-content/uploads/2019/07/poza52.jpg", "https://adpconstruct.ro/wp-content/uploads/2019/07/poza52.jpg"]
  },
  {
    name: "Site 2",
    url: "https://www.google.ro/",
    description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
    site_image: ["https://adpconstruct.ro/wp-content/uploads/2019/07/poza52.jpg", "https://adpconstruct.ro/wp-content/uploads/2019/07/poza52.jpg", "https://adpconstruct.ro/wp-content/uploads/2019/07/poza52.jpg"]
  }
]

const projectHTML = (data) => {
  let html = ''
  html += '<div class="container">'
  html += '<div class="row">'
  html += '<div class="col-md-6">'
  html += `<h2>${data.name}</h2>`
  html += `<a href="${data.url}">${data.url}</a>`
  html += `<p>${data.description}'</p>`
  html += '</div>'
  html += '<div class="col-md-6">'
  data.site_image.forEach((e, i, a) => {
    html += `<img src="${data.site_image[i]}"`
    i === a.length - 1 ? html += '' : html += '<br />'
  })
  html += '</div>'
  html += '</div>'
  html += '</div>'

  return html
}

function deosebitProject(arr) {
  const r = Math.floor(Math.random() * arr.length);
  document.getElementById('content').innerHTML = projectHTML(arr[r])
}

const btn = document.getElementById('btn')
btn.addEventListener('click', function(e) {
  deosebitProject(arr)
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

<div>
  <p id="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce blandit, erat ac lobortis tristique, eros eros tristique enim, at imperdiet lectus orci fermentum ex. Suspendisse at nisl pretium, congue nunc sit amet, rutrum lectus. Integer eu luctus
    metus. Duis placerat finibus urna eu euismod. Vestibulum mollis viverra lacinia. Curabitur odio elit, venenatis eget congue sit amet, sagittis bibendum risus. Donec pretium id justo nec elementum. Duis interdum non ligula at imperdiet. Nunc ultricies
    ac arcu id aliquet. Ut vitae risus magna. Curabitur mollis placerat tortor, nec finibus mi elementum nec. Pellentesque vitae tortor elementum, porttitor magna sit amet, dapibus nisl. Nullam sed dolor id enim tempus porttitor. Curabitur eleifend condimentum
    nisl, id placerat purus semper sed. Nulla facilisi. Donec vehicula tempor nulla a tempor. Nulla quis rhoncus elit. Aenean sagittis auctor turpis vel pharetra. Donec est nunc, molestie sit amet ullamcorper sed, facilisis nec sapien. Mauris mauris quam,
    porta sed ante ut, egestas ultricies augue. Pellentesque ornare arcu ac vestibulum mattis. Sed nec malesuada turpis. Cras aliquam turpis nec justo tempus finibus. Morbi et luctus est.Curabitur eget malesuada neque. Lorem ipsum dolor sit amet, consectetur
    adipiscing elit. Maecenas sed sagittis arcu. Maecenas quis orci quis lorem luctus feugiat placerat in tellus.</p>
</div>
<div id="our-project">
  <button id="btn">View Project</button>
</div>

EDIT

const projectHTML = (data) => {} is an arrow function (This is an arrow: =>). Most of the time arrow functions and traditional functions are interchangeable - most of the time!

The other difference is I used const instead of var. In this simple case this also makes no difference - const is a block-scoped variable, var is not.

data in my snippet is not a special object. I could have named it doggieDoo or anything (not reserved term, of course). this is a reserved keyword in JS.

So, basically they mean the same thing:

const projectHTML = (data) => {}
/*is the same as*/
var projectHTML = function(data) {}

I must emphasize though, that they do the same thing in this case!

You can read a lot more here:

Arrow functions vs traditional functions

Variable declarations:

this keyword:

I think you'll get much more information by looking at the linked contents, than if I started explaining :)

Share:
111

Related videos on Youtube

Pruteanu Alexandru
Author by

Pruteanu Alexandru

Updated on December 14, 2022

Comments

  • Pruteanu Alexandru
    Pruteanu Alexandru over 1 year

    I saw in a project a function that promoted random values from different objects in JavaScript and display content inside HTML tag,I want to make something like that but different. When I a button to take random value to a single object and display it inside a div.

    I create some object in JS and a action when click a button display object but I don't know how to put all content inside a div and to take random information.

    function deosebitProject() {
      var site_1 = {
        name: "Site 1",
        url: "https://www.google.ro/",
        description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
        site_image: ["https://adpconstruct.ro/wp-content/uploads/2019/07/poza52.jpg", "https://adpconstruct.ro/wp-content/uploads/2019/07/poza52.jpg", "https://adpconstruct.ro/wp-content/uploads/2019/07/poza52.jpg"]
      }
    
      var site_2 = {
        name: "Site 2",
        url: "https://www.google.ro/",
        description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
        site_image: ["https://adpconstruct.ro/wp-content/uploads/2019/07/poza52.jpg", "https://adpconstruct.ro/wp-content/uploads/2019/07/poza52.jpg", "https://adpconstruct.ro/wp-content/uploads/2019/07/poza52.jpg"]
      }
    
      document.write(
        '<div class="container">',
        '<div class="row">',
        '<div class="col-md-6">',
        '<h2>' + site_1.name + '</h2>',
        '<a href="' + site_1.url + '">' + site_1.url + '</a>',
        '<p>' + site_1.description + '</p>',
        '</div>',
        '<div class="col-md-6">',
        '<img src="' + site_1.site_image[0] + '"><br /> <img src =' + site_1.site_image[1] + '"><br /> <img src = "' + site_1.site_image[2] + '">',
        '</div>',
        '</div>',
        '</div>'
      );
    
      document.write(
        '<div class="container">',
        '<div class="row">',
        '<div class="col-md-6">',
        '<h2>' + site_2.name + '</h2>',
        '<a href="' + site_2.url + '">' + site_2.url + '</a>',
        '<p>' + site_2.description + '</p>',
        '</div>',
        '<div class="col-md-6">',
        '<img src="' + site_2.site_image[0] + '"><br /> <img src =' + site_2.site_image[1] + '"><br /> <img src = "' + site_2.site_image[2] + '">',
        '</div>',
        '</div>',
        '</div>'
      );
    }
    <!doctype html>
    <html>
    
    <head>
      <title>Javascript Challange 1</title>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
      <script type="text/javascript" src="random.js"></script>
    </head>
    
    <body>
      <div>
        <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce blandit, erat ac lobortis tristique, eros eros tristique enim, at imperdiet lectus orci fermentum ex. Suspendisse at nisl pretium, congue nunc sit amet, rutrum lectus. Integer eu luctus
          metus. Duis placerat finibus urna eu euismod. Vestibulum mollis viverra lacinia. Curabitur odio elit, venenatis eget congue sit amet, sagittis bibendum risus. Donec pretium id justo nec elementum. Duis interdum non ligula at imperdiet. Nunc ultricies
          ac arcu id aliquet. Ut vitae risus magna. Curabitur mollis placerat tortor, nec finibus mi elementum nec. Pellentesque vitae tortor elementum, porttitor magna sit amet, dapibus nisl. Nullam sed dolor id enim tempus porttitor. Curabitur eleifend
          condimentum nisl, id placerat purus semper sed. Nulla facilisi. Donec vehicula tempor nulla a tempor. Nulla quis rhoncus elit. Aenean sagittis auctor turpis vel pharetra. Donec est nunc, molestie sit amet ullamcorper sed, facilisis nec sapien. Mauris
          mauris quam, porta sed ante ut, egestas ultricies augue. Pellentesque ornare arcu ac vestibulum mattis. Sed nec malesuada turpis. Cras aliquam turpis nec justo tempus finibus. Morbi et luctus est.Curabitur eget malesuada neque. Lorem ipsum dolor
          sit amet, consectetur adipiscing elit. Maecenas sed sagittis arcu. Maecenas quis orci quis lorem luctus feugiat placerat in tellus.
        </p>
      </div>
      <div id="our-project">
        <button onclick="deosebitProject()">View Project</button>
      </div>
    </body>
    
    </html>
  • Wichuda Tanyongmaskul
    Wichuda Tanyongmaskul about 9 years
    Thanks a lot for the kind answer. I will try as the above suggestion and Will get back if get a problem
  • Pruteanu Alexandru
    Pruteanu Alexandru over 4 years
    thank you very much !!!But I have one question how I can display the random content inside <div id="our-project"></div> I mean to change only the div not the the entire page.
  • muka.gergely
    muka.gergely over 4 years
    Change the content in document.getElememtById to our-project. That part selects the DOM container element where the created HTML will be appended.
  • Pruteanu Alexandru
    Pruteanu Alexandru over 4 years
    thank you I a begginer in programming language,I dont relly undestud how js works.
  • Pruteanu Alexandru
    Pruteanu Alexandru over 4 years
    var projectHTML = function(data){} vs const projectHTML = (data) => {} I use the old versyon but I have a question how the parameter(data) works how this take data from array now.I know a method for exampe make a variablere to storahe aboject data using "this" .
  • muka.gergely
    muka.gergely over 4 years
    Somehow I felt that you’re beginning to learn & practice JS! ;) As long as you show an effort StackOverflow is a welcoming place to learn (a lot) - doesn’t matter what level you are at.
  • muka.gergely
    muka.gergely over 4 years
    I’m only using my phone now - let me look at your question regarding data a bit later.
  • muka.gergely
    muka.gergely over 4 years
    I edited my answer and gave a lot of references so you can get a broad understanding of the topics your question touches. There're a lot of examples so you can practice these.
  • Pruteanu Alexandru
    Pruteanu Alexandru over 4 years
    new I see you are using parameter data after random to generate the content in html.