user3475725 user3475725 - 1 month ago 11
jQuery Question

Load div using Jquery or Javascript

I have 5 div on one page. Something like that:

<div id="div1"> some content </div>
<div id="div2"> some content </div>
<div id="div3"> some content </div>
<div id="div4"> some content </div>
<div id="div5"> some content </div>
<button> Load More </button>


I want to make only first div loaded, after clicks button Load more, then I want to be loaded second div, if he/she clicks one more time Load more button, I want to be loaded third div (but first two divs shouldn't hide). Is it possible using Javascript or Jquery?

I'm newbie in Javascript. I tried doing using this: http://jsfiddle.net/vendettamit/QB8Hv/ Tried different versions, but I couldn't :(

I don't need to make class hidden and display: none using css. I want this divs not to be loaded, if user doesn't click on button, because I have big traffic.

Nvj Nvj
Answer

If I understand your question correctly.. you want to load a different image when the user clicks the second time. For that, you need to specify a different image source when the user clicks on it the second time.

There are two ways you could do this. One is to build a JavaScript array that will store the image source paths. When the user clicks on the button successively, take the next element from the array (by using an incremental variable).

For example,

var imageSources = [
    "image1.jpg", 
    "image2.jpg", 
    "image3.jpg", 
    "image4.jpg", 
    "image5.jpg", 
]

Then when the user clicks on the button,

function onClick()
{
     // Get number of image tags already loaded
     var numberOfDivsLoaded = document.getElementById("parentDiv").getElementsByTagName('img').length;

     // Get the next array element
     var nextImageSource = imageSources[numberOfDivsLoaded + 1]

     // Then create an append a new div containing this image to the parent div
}

The other way is to use AJAX. When the user clicks on the button, send an AJAX request to load the next image to your back-end script.

Comments