1

I have a div called masterdiv, inside this div there are 3 other div div1, div2, and div3,

This is the html for these html:

<div id="masterdiv" class="masterdivclass">

        <div id="div1"><img class="div1class" src="image1.jpg" id="div1id" /></div>

        <div id="div2"><img class="div2class" src="image2.jpg" id="div2id" /></div>

        <div id="div3"><img class="div3class" src="image3.jpg" id="div3id" /></div>

</div>

I also have another div:

<div id=”reload”><img src="reload.png" width="200" height="70" onclick=loadDIV();></div>

What I’m trying to do is to reload the masterdiv div whenever the reload div is clicked on. Hiding and then showing the div isn’t enough as I need the content to be reloaded when the refresh div is clicked on. I don’t want to reload the entire page, just the masterdiv which contains the 3 other div. But I’m not certain this is possible.

I’m trying to do it with this Javascript function:

<script type="text/javascript">
       function loadDiv(){
       $("<div id="masterdiv" class="masterdivclass">

        <div id="div1"><img class="div1class" src="image1.jpg" id="div1id" /></div>

        <div id="div2"><img class="div2class" src="image2.jpg" id="div2id" /></div>

        <div id="div3"><img class="div3class" src="image3.jpg" id="div3id" /></div>

</div>").appendTo("body");
       }
    </script>

This isn’t working, I think maybe I'm going about this in the wrong way? Maybe I’m missing something very simple here? I’d really appreciate any help with this, thank you in advance!

UPDATE

After reconsidering my project's requirements, I need to change part of my question, I now need to randomise the images displayed in the divs, and have a new random image load every time the reload div is clicked on. I also need to remove each class that’s currently in each of the three divs and then reattach the same classes to the divs (if I don’t remove and reattach the classes then the divs just display the plain images without any class/effect applied to them, it seems like I need to reload the class every time I load an image into a div in order for the class/effect to be applied successfully).

I have 5 images, and I’m using each div’s id tag to attach a random image to each div.

First I’m assigning the 5 different images to 5 different ids:

<script>
document.getElementById('sample1').src="images/00001.jpg";
document.getElementById('sample2').src="images/00002.jpg";
document.getElementById('sample3').src="images/00003.jpg";
document.getElementById('sample4').src="images/00004.jpg";
document.getElementById('sample5').src="images/00005.jpg";
</script> 

And then I’m trying to use the following Javascript to load a randomised id (and its assigned image) to each of the 3 divs when the reload div is clicked:

<script>
$(function() {
    $('#reload').on('click',function(){
        $("#masterdiv").find("div[id^='div']").each(function(index){

//First, remove and reattach classes “div1class”, “div2class” and “div3class” 
//from “easyDIV”, “mediumDIV” and “hardDIV” respectively:
            $(“#easyDIV”).removeClass('div1class');
            $(“#easyDIV”).addClass('div1class');
            $(“#mediumDIV”).removeClass('div2class');
            $(“#mediumDIV”).addClass('div2class');
            $(“#hardDIV”).removeClass('div3class');
            $(“#hardDIV”).addClass('div3class');


//Get a random number between 1 and 5, then attach it to “sample”, 
//so that the result will be either “sample1”, “sample2”, “sample3”, “sample4” or “sample5”, 
//call this variable “variablesample”:
    var num = Math.floor(Math.random() * 5 + 1); 
       variablesample = "sample" +num;

//Attach this randomised id to all three divs using “variablesample”:
           jQuery(this).prev("easyDIV").attr("id",variablesample);
           jQuery(this).prev("mediumDIV").attr("id",variablesample);
           jQuery(this).prev("hardDIV").attr("id",variablesample);

        });
        var p = $("#masterdiv").parent();
        var el = $("#masterdiv").detach();
        p.append(el);
    });
});
</script> 

I’m trying to make it so that all 3 divs will show the same randomised picture (that’s why they’re all sharing the variable “variablesample”), and each div will reload its own class/effect (div1class, div2class and div3class) but it’s not working. I’m not sure if it’s correct to use jQuery inside a Javascript function, or if my syntax for updating the ids of the divs is incorrect.

Perhaps my logic to solving this problem is all wrong? I’d really appreciate any more help with this problem. Thanks again in advance!

Emily
  • 1,103
  • 2
  • 18
  • 38
  • Are you changing the content somehow, is that why you want to reload it? Why is hiding/showing not enough? – turbopipp Sep 29 '15 at 06:39
  • 1
    if you want to reload the image, target that in stead of the div. See this answer for how to reload a different image with the same url. http://stackoverflow.com/questions/1077041/refresh-image-with-a-new-one-at-the-same-url – timo Sep 29 '15 at 06:40
  • Hi @turbopipp yes that's what I'm doing, thanks for your reply, I've left a more detailed comment on your answer. – Emily Sep 29 '15 at 07:59
  • Could you also update with your current html please? :) Or better yet, make a jsfiddle of what you have done so far. It would make it much easier to help out :) – turbopipp Oct 01 '15 at 12:40

4 Answers4

2

For posterities sake, I will leave all my answers to all the edits to the original question.. I hope we reached the right question eventually..? :)

First answer (use of .detach() to "reload" an element): jsfiddle demo

Second answer (random class, as asked for): jsfiddle demo

Third answer (random image, but same image on all 3, and 3 class on/off switching): jsfiddle demo

$(function() {
    var imageArray = [
        'https://placehold.it/40x40',
        'https://placehold.it/80x40',
        'https://placehold.it/120x40',
        'https://placehold.it/160x40',
        'https://placehold.it/200x40'];
    reloadImages(imageArray);
    $('#reload').on('click',function(){
        $( "#masterdiv img[id^='div']" ).each(function(index){
            $(this).removeClass("div"+(index+1)+"class");
            $(this).fadeOut( "slow", function() {
                if(index==0) {
                    reloadImages(imageArray);
                }
                $(this).addClass("div"+(index+1)+"class");
                $(this).fadeIn();

            });
        });
    });
});


function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}

function reloadImages(array){
    shuffleArray(array);
    for(var i=0;i<3;i++){
        // places the first image into all divs, change 0 to i if you want different images in each div
        document.getElementById('div'+(i+1)+'id').src=array[0];
    }
}
.div1class {
    border:2px dashed #0F0;
}
.div2class {
    border:2px dashed yellow;
}
.div3class {
    border:2px dashed red;
}
#reload {
    background-color:blue;
    width:100px;
    height:30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id='reload'>Click here</div>

<div id="masterdiv" class="masterdivclass">
    <div id="div1">
        <img src="https://placehold.it/20x40" class="div1class" id="div1id" />
    </div>
    <div id="div2">
        <img src="https://placehold.it/20x40" class="div2class" id="div2id" />
    </div>
    <div id="div3">
        <img src="https://placehold.it/20x40" class="div3class" id="div3id" />
    </div>
</div>
turbopipp
  • 1,193
  • 2
  • 11
  • 25
  • Hi @turbopipp thanks for your reply, I'm trying your method but I have one problem, the reason I need to reload the parent div is because the ids for the child divs "div1id", "div2id" and "div3id" are linked to a function which generates and attaches a random effect on the images (the ids apply a different effect to the images every time the page is reloaded), I want this to occur by just refreshing the parent div, instead of the whole page, but at the minute, while your method does make the divs disappear and reappear, the effect on the images (caused by their id) stays the same. – Emily Sep 29 '15 at 07:58
  • is it possible to append the ids to the child divs as well? Thanks again. – Emily Sep 29 '15 at 07:59
  • 1
    I think a better solution would be to use `.addClass()` and `.removeClass()`, and let the classname decide the random effects. You can then traverse the divs inside the main div, and addClass to random indexes. I can create an updated example for you soon(somewhat busy atm). – turbopipp Sep 29 '15 at 08:51
  • 1
    Updated my answer now, hope it's to your satisfaction :) I don't know much about the mysterious function that makes a random effect, but I created a small example for you to see the logic behind it. – turbopipp Sep 29 '15 at 09:19
  • How did it work out for you? I noticed you didn't mark any answers as correct yet :) – turbopipp Sep 30 '15 at 21:42
  • 1
    Hi @turbopipp thanks so much for your answer! I've trying different things out with your code but I realised I needed to change the scope of my question to include randomising the image displayed in the 3 divs. I've written an update at the bottom of my question, which details the change and includes my latest attempt to solve the problem by using the code you provided. I think I may be going about it in the wrong way though and would really appreciate it if you could take a look at my current attempt, thanks so much again for your time! – Emily Oct 01 '15 at 08:58
  • Quick and dirty fix: [updated my previous fiddle](http://jsfiddle.net/turbopipp/sq9ycurb/). I can clean it up later, gotta leave the house now. :) Hope it helps. – turbopipp Oct 01 '15 at 13:39
  • I updated my answer now. If you do feel it is still not correct, please post all your code, including the css effect function you mention, and your new html code. And also a jsfiddle of your own would help speed up the process. :) – turbopipp Oct 02 '15 at 04:58
  • Hi @turbopipp thanks again for your help with this, your answer definitely works for removing a class and randomising the image at the same time, unfortunately for some reason it's not working with what I'm trying to do, but your answer deserves to be marked as correct, if you would like to see what I'm trying to do I've uploaded a fiddle here: http://jsfiddle.net/onwe25fw/ thank you again! – Emily Oct 03 '15 at 09:36
  • Thanks, and yes that explains it. If you inspect the code after initialization, you will see the image tag is gone, and replaced with a `.jqPuzzle`-div, therefore targeting the image wont do you any good. I'm sorry, this question grew very complex. I suggest you start another question with the fiddle you made to get some fresh eyes on it, and tag the question with `jqpuzzle` as well, because I think your answer lies within that plugin, or customizing that plugin somehow. Best of luck, I will keep an eye out for the new question, and provide help if I can. :) – turbopipp Oct 03 '15 at 16:06
  • I tried `$( "#masterdiv > div[id$='DIV'] > .jqPuzzle > .jqp-wrapper" ).first().css('background-image')` to get the image URL, but it returned `none`..so I'm at a loss atm. The answer is inside the plugin, or to manipulate it somehow, or making a listener for some change it does. – turbopipp Oct 03 '15 at 16:10
1

try:

function loadDiv(){

    $("#masterdiv").load(location.href + " #masterdiv");

}

Here's the code pen demo: http://codepen.io/anon/pen/xwgRWm

Nishanth Matha
  • 5,714
  • 2
  • 16
  • 27
  • Hi @nishanth-matha thanks for your comment, I've tried that method but it ended up creating a copy of all the page elements, the result was the page loaded a second time on top of itself. And all the page elements became duplicated, so instead of having 5 buttons on the page, 10 buttons appeared when this function ran. I'm not sure what caused this. – Emily Sep 29 '15 at 07:52
  • hey @emily that shouldn't be the case. I've edited the ans and attached the copedepen demo. Have alook at that. If you still have problems post your code in a codepen and share the link with us. – Nishanth Matha Sep 30 '15 at 00:16
1

If content of container is not being changed dynamically then there is no point reloading it. appendTo wiil append DOM in existing DOM structure, you will need html() here which will replace the content inside container. Also note you had typo here onclick=loadDiv();

HTML:

<div id="masterdiv" class="masterdivclass">

    <div id="div1"><img class="div1class" src="image1.jpg" id="div1id"/></div>

    <div id="div2"><img class="div2class" src="image2.jpg" id="div2id"/></div>

    <div id="div3"><img class="div3class" src="image3.jpg" id="div3id"/></div>

</div>
<div id="reload"><img src="reload.png" width="200" height="70" onclick=loadDiv();></div>

JS:

function loadDiv() {
    $("#masterdiv").html('<div id="div1"><img class="div1class" src="image1.jpg" id="div1id" /></div>\
            <div id="div2"><img class="div2class" src="image2.jpg" id="div2id" /></div>\
            <div id="div3"><img class="div3class" src="image3.jpg" id="div3id" /></div>');
}
Rayon
  • 34,175
  • 4
  • 40
  • 65
1

Line breaks and un-escaped quotes are why the functions is not working.

function loadDiv(){
    $('#masterdiv').remove();
    $("<div id='masterdiv' class='masterdivclass'><div id='div1'><img class='div1class' src='image1.jpg' id='div1id' /></div><div id='div2'><img class='div2class' src='image2.jpg' id='div2id' /></div><div id='div3'><img class='div3class' src='image3.jpg' id='div3id' /></div></div>").appendTo("body");
}
rrk
  • 14,861
  • 4
  • 25
  • 41