I have 28 divs, all floated left with a width & height of 200px with 5px margins on the right and bottom of each div. I have successfully figured out how to place other divs after other divs via jquery. I did it like so.
$( '.inner:nth-child(10)' ).after( '<div class="test">');
This works great! But what I would like to do is change the “inner” div classes nth-child position based on browser width and I’ve managed to get it working, somewhat.
Here is the code I’m using:
var $window = $(window);
function checkWidth() {
var windowsize = $window.width();
if (windowsize > 440) {
$( '.inner:nth-child(10)' ).after( '<div class="test">');
}
}
// Execute on load
checkWidth();
// Bind event listener
$(window).resize(checkWidth);
So I’m telling my browser to display the div “inner” after the 10th “test” div when the viewers browser width exceeds 440px. Again, this works, somewhat. It successfully displays the “inner” div in the correct position when the browser width exceeds 440px, and it also doesn’t show the div when the browser width is below 440px. But the huge problem is that whenever the window is resized, a whole bunch of divs start to be created. This is very puzzling to me. Here is the jsFiddle to demonstrate my issue:
You will see that at a glance it appears to be working fine but if you resize the HTML window within jsfiddle, a bunch of divs start to be created. In actuality, the div should always remain in the correct spot, right after the 10th inner div. Instead, it just creates a bunch of other divs when the window is resized.
If anyone could help me out with a solution to this problem and get this little issue working properly within jsfiddle, it would mean a ton to me! 🙂
Can you try this?
Is this what you wanted? In your version the resize function is calling .after() many times, adding a lot of new divs. It should work this way
EDIT:
With @pete s suggestion it’s easyer to add new colored divs.
You just have to add the css rule for the test1 class.