How to remove random div js - javascript

http://prntscr.com/p9u6f9
I create random divs using:
let div1 = 'div_list';
let div2 = div1 + [Math.floor(Math.random()*24)];
node.setAttribute('id', div2);
And I want remove div using button, but how can I remove this, not having ID? Because the ID is random.
function remove() {
console.log(div);
let remove = document.getElementById(??????????);
remove.remove();
}

Add an eventListener upon the creation of the node and call remove with the generated id :
let div1 = "div_list";
let div2 = div1 + [Math.floor(Math.random() * 24)];
node.setAttribute("id", div2);
node.addEventListener("click", () => remove(div2)); // add the event listener for the button of deletion if you're creating it with the div
function remove(id) {
console.log(id);
let remove = document.getElementById(id);
remove.remove();
}

Just try this example, it's 100% working.
function randRemove() {
var divCount = 5;
var randNumber = Math.floor(Math.random() * divCount) + 1;
var randSelect = document.getElementById("div-" + randNumber);
randSelect.remove();
alert("Div Removed: " + "div-" + randNumber);
}
.just-style {
display: inline-block;
width: 300px;
height: 100px;
margin: 20px;
}
<button id="randRemove" onclick="randRemove()">Remove Random Div</button>
<div id="main-div">
<div id="div-1" class="just-style" style="background-color: red;"></div>
<div id="div-2" class="just-style" style="background-color: blue;"></div>
<div id="div-3" class="just-style" style="background-color: aqua;"></div>
<div id="div-4" class="just-style" style="background-color: violet;"></div>
<div id="div-5" class="just-style" style="background-color: forestgreen;"></div>
<!--AND MORE DIV ... -->
</div>
Enjoy and good luck =D

Related

I want to change the link color randomly when i click on it. Is there any way i can do it without using buttons?

<div class="heading">
<div id="link"><a>My Name</a></div>
<div class="pro">My Career</div>
</div>
I tried to search for an answer but am just getting how to only change the background or with a button.
Find the link element.
Add a click listener to it.
On click of the link element, generate a random color and update the element's color style attribute.
Here is the demo-
// find the link element
let linkEl = document.querySelector('#link a');
// attach a click listener to it
linkEl.addEventListener('click', () => {
// Generate a random color
let color = '#' + Math.floor(Math.random() * 16777215).toString(16);
// set color to the link element
linkEl.style.color = color;
})
a {
cursor: pointer;
}
<div class="heading">
<div id="link">
<a>My Name (click me to change my color)</a>
</div>
<div class="pro">My Career</div>
</div>
Yea probably
<script>
function changeLinkColor() {
// Generate a random color in the format '#RRGGBB'
let randomColor = '#' + Math.floor(Math.random() * 16777215).toString(16);
// Get the link element
let link = document.querySelector("#link a");
// Set the link color to the random color
link.style.color = randomColor;
}
</script>
You can try this in any case:
function generateColor(){
return Math.floor(Math.random() * 255);
}
document.querySelectorAll('.anchor').forEach(el => {
el.onclick = function(e){e.target.style.backgroundColor = 'rgb('+ generateColor() + ',' + generateColor() + ','+ generateColor() + ')';
}
});
.anchor{
display: inline-block;
background:dodgerblue;
text-decoration: none;
color:#fff;
border-radius: 10px;
text-shadow: 0 0 2px #000;
padding: 10px;
margin:10px
}
<a class="anchor anchor1" href="#">click 1</a>
<div class="anchor anchor2" href="#">click 1</div>
<p class="anchor anchor3" href="#">click 1</p>
Please check this solution and let me know if its help you in any way.

JavaScript loop throught and hide all divs except one

I have a big list of getElementsById that looks like this:
let ahSummerCamps = document.getElementById("aH-summerCamps");
let ahTrekking = document.getElementById("aH-trekking");
let bpLongDistanceHiking = document.getElementById("bp-longDistanceHiking");
let bpThruHiking = document.getElementById("bp-thruHiking");
let cOceanCruising = document.getElementById("c-oceanCruising");
let cRiverCruising = document.getElementById("c-riverCruising");
let eRecreationsEvent = document.getElementById("e-recreationsEvent");
let eSportsEvent = document.getElementById("e-sportsEvents");
let phEscortedTours = document.getElementById("ph-escortedTours");
let phIndependentTours = document.getElementById("ph-independentTours");
let sPhotographicSafari = document.getElementById("s-photographicSafari");
let sCyclingSafari = document.getElementById("s-cyclingSafari");
let sAsBackcountrySkiing = document.getElementById("sAs-backcountrySkiing");
let sAsDownhillSkiing = document.getElementById("sAs-downhillSkiing");
let vChildcare = document.getElementById("v-childcare");
let vConservationAndEnvironment = document.getElementById("v-conservationAndEnvironment");
I won't go into details, is there any way that I can loop throught all of them and for example hide all except bpLongDistanceHiking and bpThruHiking .
I had this function but that is not good way for sure:
function hideAllExceptbP() {
ahSummerCamps.style.display = "none";
ahTrekking.style.display = "none";
/* ... and for all of them like this except bpLongDistanceHiking and bpThruHiking */
}
So on that way I need function for every element like:
function hideAllExceptaH() {
/* ... + 10 lines */
function hideAllExceptC() {
/* ... + 10 lines */
function hideAllExceptE() {
/* ... + 10 lines */
Function
function choice() {
backpacking.addEventListener("click", () => {
hideBackpacking();
hideSafari();
hidePackageHoliday();
showBackpackingOptions();
console.log("Backpacking");
});
So as you can see from html I have 8 divs at start, and when user click on backpacking for example function should hide all divs except bpLongDistanceHiking and bpThruHiking
Full code calling function:
HTML:
<div class="row">
<!--main divs-->
<div style="background-color: #4cc9f0" class="column" id="adventureHolidays"><p>Adventure Holidays</p></div>
<div style="background-color: #4895ef" class="column" id="backpacking"><p>Backpacking</p></div>
<div style="background-color: #4361ee" class="column" id="cruiseHolidays"><p>Cruise Holidays</p></div>
<div style="background-color: #4361ee" class="column" id="eventTravel"><p>Event Travel</p>
</div>
<div style="background-color: #3a0ca3" class="column" id="packageHoliday"><p>Package Holiday</p></div>
<div style="background-color: #480ca8" class="column" id="safari"><p>Safari</p></div>
<div style="background-color: #560bad" class="column" id="skiingAndSnowboarding"><p>Skiing and Snowboarding</p>
</div>
<div style="background-color: #7209b7" class="column" id="volunteering"><p>Volunteering</p></div>
<!--end on main divs-->
<!--sub divs-->
<div style="background-color: #4cc9f0" class="column" id="aH-summerCamps"><p>Summer camps</p></div>
<div style="background-color: #4895ef" class="column" id="aH-trekking"><p>Trekking</p></div>
<div style="background-color: #4361ee" class="column" id="bP-longDistanceHiking"><p>Long Distance Hiking</p></div>
<div style="background-color: #4361ee" class="column" id="bP-thruHiking"><p>Thru Hiking</p></div>
<div style="background-color: #3a0ca3" class="column" id="c-oceanCruising"><p>Ocean Cruising</p></div>
<div style="background-color: #480ca8" class="column" id="c-riverCruising"><p>River Cruising</p></div>
<div style="background-color: #560bad" class="column" id="e-recreationsEvent"><p>Recreations Events</p></div>
<div style="background-color: #7209b7" class="column" id="e-sportsEvents"><p>Sports events</p></div>
<div style="background-color: #4cc9f0" class="column" id="pH-escortedTours"><p>Escorted Tours</p></div>
<div style="background-color: #4895ef" class="column" id="pH-independentTours"><p>Independent Tours</p></div>
<div style="background-color: #4361ee" class="column" id="s-photographicSafari"><p>Photographic Safari</p></div>
<div style="background-color: #4895ef" class="column" id="s-cyclingSafari"><p>Cycling Safari</p></div>
<div style="background-color: #3a0ca3" class="column" id="sAs-backcountrySkiing"><p>Backcountry skiing</p></div>
<div style="background-color: #560bad" class="column" id="sAs-downhillSkiing"><p>Downhill skiing</p></div>
<div style="background-color: #4361ee" class="column" id="v-childcare"><p>Childcare</p></div>
<div style="background-color: #4895ef" class="column" id="v-conservationAndEnvironment"><p>Conservation And
Environment</p></div>
</div>
<script type="text/javascript" th:src="#{/js/index.js}"></script>
js:
let adventureHolidays = document.getElementById("adventureHolidays");
let backpacking = document.getElementById("backpacking");
let cruiseHolidays = document.getElementById("cruiseHolidays");
let eventTravel = document.getElementById("eventTravel");
let packageHoliday = document.getElementById("packageHoliday");
let safari = document.getElementById("safari");
let skiingAndSnowboarding = document.getElementById("skiingAndSnowboarding");
let volunteering = document.getElementById("volunteering");
/*End of inserting main variables*/
/*sub variables*/
let ahSummerCamps = document.getElementById("aH-summerCamps");
let ahTrekking = document.getElementById("aH-trekking");
let bPLongDistanceHiking = document.getElementById("bP-longDistanceHiking");
let bPThruHiking = document.getElementById("bP-thruHiking");
let cOceanCruising = document.getElementById("c-oceanCruising");
let cRiverCruising = document.getElementById("c-riverCruising");
let eRecreationsEvent = document.getElementById("e-recreationsEvent");
let eSportsEvent = document.getElementById("e-sportsEvents");
let phEscortedTours = document.getElementById("ph-escortedTours");
let phIndependentTours = document.getElementById("ph-independentTours");
let sPhotographicSafari = document.getElementById("s-photographicSafari");
let sCyclingSafari = document.getElementById("s-cyclingSafari");
let sAsBackcountrySkiing = document.getElementById("sAs-backcountrySkiing");
let sAsDownhillSkiing = document.getElementById("sAs-downhillSkiing");
let vChildcare = document.getElementById("v-childcare");
let vConservationAndEnvironment = document.getElementById("v-conservationAndEnvironment");
/*end of subs variables*/
const divs = ["adventureHolidays", "backpacking", "cruiseHolidays", "eventTravel", "packageHoliday", "safari", "skiingAndSnowboarding", "volunteering", "aH-summerCamps", "aH-trekking", "bP-longDistanceHiking", "bP-thruHiking", "c-oceanCruising", "c-riverCruising", "e-recreationsEvent", "e-sportsEvents", "ph-escortedTours", "ph-independentTours", "s-photographicSafari", "s-cyclingSafari", "sAs-backcountrySkiing", "v-conservationAndEnvironment", "sAs-downhillSkiing", "v-childcare"]
.map(id => document.getElementById(id)); // gives you an array of those elements
function hideAllDivsExcept(id) {
for (const div of divs) div.hidden = !div.id === id;
}
window.onload = function () {
choice();
};
/* start of function choice for user clicks*/
function choice() {
backpacking.addEventListener("click", () => {
hideAllDivsExcept('adventureHolidays');
console.log("Backpacking");
})
}
CSS:
* {
box-sizing: border-box;
}
/* Create three equal columns that floats next to each other */
.column {
float: left;
width: 33.33%;
padding: 10px;
}
/* Clear floats after the columns */
.row:after {
content: "";
/*
display: table;
*/
clear: both;
}
I'm getting:
index.js:38 Uncaught TypeError: Cannot read properties of null (reading 'id')
at hideAllDivsExcept (index.js:38:47)
at HTMLDivElement.<anonymous> (index.js:51:9)
And that is this
function hideAllDivsExcept(id) {
this > for (const div of divs) div.hidden = !div.id === id;
}
One approach to the problem is as below, with explanatory comments in the code:
// defining a named function to handle clicks on the 'filter' elements, that takes one
// argument, a reference to the Event Object:
const showRelevant = (evt) =>{
// caching a reference to the element to which the function is bound as the
// event-handler:
let source = evt.currentTarget,
// retrieving the attribute-value from the custom data-* attribute, using the
// HTMLElement.dataset API:
category = source.dataset.category;
// retrieving all <div> elements that do not have a "data-category" attribute which
// are the children of a .row element; we iterate over that collection using
// NodeList.prototype.forEach():
document.querySelectorAll('.row > div:not([data-category])').forEach(
// using an Arrow function we pass in a reference to the current
// Node of the NodeList over which we're iterating:
(el) => {
// we split the element's id property-value at the '-' character,
// and retrieve the first element of the resulting Array:
let prefix = el.id.split('-')[0];
// if the chosen category is exactly equal to 'all':
if (category === 'all') {
// we want to show all elements, therefore we set the hidden property
// of every element to false; so every element is shown:
el.hidden = false;
} else {
// otherwise, if the category is not equal to the prefix (above) the
// assessment results in true and so the element is hidden; if the
// category is equal to the prefix (therefore the current element is
// one we wish to see) the assessment results in false, and so the
// element is shown:
el.hidden = category !== prefix;
}
})
};
// here we retrieve all child elements with a "data-category" attribute of a .row element,
// and iterate over that NodeList with NodeList.prototype.forEach():
document.querySelectorAll('.row > [data-category]').forEach(
// using an Arrow function we pass in a reference to the current Node of the NodeList,
// and use EventTarget.addEventListener() to bind the showRelevant() function (note the
// deliberate lack of parentheses) as the event-handler for the 'click' event:
(el) => el.addEventListener('click', showRelevant)
)
:root {
--h-1: 212;
--h-2: 194;
--s: 84%;
--l: 62%;
--c-l: var(--l);
--bgc-l: var(--l);
}
* {
box-sizing: border-box;
}
.row {
/* rather than using float, I've used display: flex: */
display: flex;
/* the default of flex elements is:
flex-direction: row;
flex-wrap: nowrap;
flex-flow is a shorthand to update both those values;
here I've specified:
flex-direction: row;
flex-wrap: wrap;
*/
flex-flow: row wrap;
/* adjust to taste, but this replicates the behaviour of
floating in that elements on an incomplete row will
align to the start of the row: */
justify-content: start;
/* placing a 0.2em margin on the block-axis of the element;
in a language such as English (left-to-right, top-to-bottom)
that aligns to the top (margin-block-start) and bottom
(margin-block-end) margins: */
margin-block: 0.2em;
}
.row > * {
box-shadow: inset 0 0 0 3px currentColor, inset 0 0 0 4px #fff;
/* basing the width of the elements - using the flex-basis
property - to 33%: */
flex-basis: 33%;
padding: 10px;
}
.row > *:nth-child(even) {
/* using CSS custom properties to set color and
background-color: */
color: hsl(var(--h-1) var(--s) var(--c-l));
background-color: hsl(var(--h-2) var(--s) var(--bgc-l));
}
.row > *:nth-child(odd) {
color: hsl(var(--h-2) var(--s) var(--c-l));
background-color: hsl(var(--h-1) var(--s) var(--bgc-l));
}
.row > *:nth-child(even):hover,
.row > *:nth-child(odd):hover {
/* manipulating the CSS custom properties with the
calc function to make the color darker (by decreasing
the lightness) and the background-color lighter (by
increasing the lightness): */
--c-l: calc(var(--l)*0.5);
--bgc-l: calc(var(--l) * 1.2);
}
<div class="row">
<!--main divs-->
<!-- I've added a custom data-* attribute to each of the elements that would
constitute a 'filter' element; the attribute-value is all the initial
letters of the words written as camel-case, so:
'Adventure Holidays' => 'AH' => 'aH' -->
<div id="adventureHolidays" data-category="aH">
<p>Adventure Holidays</p>
</div>
<div id="backpacking" data-category="bP">
<p>Backpacking</p>
</div>
<div id="cruiseHolidays" data-category="cH">
<p>Cruise Holidays</p>
</div>
<div id="eventTravel" data-category="eT">
<p>Event Travel</p>
</div>
<div id="packageHoliday" data-category="pH">
<p>Package Holiday</p>
</div>
<div id="safari" data-category="s">
<p>Safari</p>
</div>
<div id="skiingAndSnowboarding" data-category="sAS">
<p>Skiing and Snowboarding</p>
</div>
<div id="volunteering" data-category="v">
<p>Volunteering</p>
</div>
<div data-category="all">
<p>Show all</p>
</div>
<!--end on main divs-->
</div>
<!-- this isn't essential, but I prefer to separate the 'filters' from the elements to be filtered: -->
<div class="row">
<!--sub divs-->
<!-- I've changed the id prefix of these elements to match the 'data-category' value from the
'filter' <div> elements: -->
<div id="aH-summerCamps">
<p>Summer camps</p>
</div>
<div id="aH-trekking">
<p>Trekking</p>
</div>
<div id="bP-longDistanceHiking">
<p>Long Distance Hiking</p>
</div>
<div id="bP-thruHiking">
<p>Thru Hiking</p>
</div>
<div id="cH-oceanCruising">
<p>Ocean Cruising</p>
</div>
<div id="cH-riverCruising">
<p>River Cruising</p>
</div>
<div id="eT-recreationsEvent">
<p>Recreations Events</p>
</div>
<div id="eT-sportsEvents">
<p>Sports events</p>
</div>
<div id="pH-escortedTours">
<p>Escorted Tours</p>
</div>
<div id="pH-independentTours">
<p>Independent Tours</p>
</div>
<div id="s-photographicSafari">
<p>Photographic Safari</p>
</div>
<div id="s-cyclingSafari">
<p>Cycling Safari</p>
</div>
<div id="sAS-backcountrySkiing">
<p>Backcountry skiing</p>
</div>
<div id="sAS-downhillSkiing">
<p>Downhill skiing</p>
</div>
<div id="v-childcare">
<p>Childcare</p>
</div>
<div id="v-conservationAndEnvironment">
<p>Conservation and Environment</p>
</div>
</div>
JS Fiddle demo.
References:
Arrow functions.
data-* attributes.
document.querySelectorAll().
Event.
EventTarget.addEventListener().
HTMLElement.dataset API.
HTMLElement.hidden property.
NodeList.prototype.forEach().
String.prototype.split().
Add an id to your main div with class 'row', e.x. daDiv then iterate and perform whatever you want checking id attribute of each one
$('#daDiv').children('div').each(function () {
if ($(this).attr('id') !== 'bP-longDistanceHiking' && $(this).attr('id') !== 'bP-thruHiking') {
$(this).hide();
}
});
CodePen
Example
UPDATE
You can even make a function
function hideExcept(arr) {
$('#daDiv').children('div').each(function () {
if (!arr.includes($(this).attr('id')))
$(this).hide();
});
}
hideExcept(['bP-longDistanceHiking', 'bP-thruHiking']); // hide all except bP-longDistanceHiking and bP-thruHiking

Background image swap animation

I have a grid and each div has a background image. I am trying to create a fade out/in image swapping effect. Currently I'm getting two random divs and inserting one background-image URL into the other. Problem is, after a while all the images wind up the same. I think I need to reset the background URL to the original value (image) each time, but I'm not sure how to do that.
So the order would be:
original image fades out,
new image fades in,
new image fades out,
original image fades in
Any help greatly appreciated!
Currently I have this fiddle:
JS:
var $squares = $('.box');
function imgFade() {
var square1 = $squares.eq([Math.floor(Math.random()*$squares.length)])
var square2 = $squares.eq([Math.floor(Math.random()*$squares.length)])
var square1Url = square1.css('background-image').replace(/(url\(|\)|")/g, '');
var square2Url = square2.css('background-image').replace(/(url\(|\)|")/g, '');
$(square1).fadeOut(1500, function() {
$(this).css("background-image", "url(" + square2Url + ")");
$(this).fadeIn(1500);
});
timeoutId = setTimeout(imgFade, 1500);
}
imgFade();
HTML:
<div class="grid-container">
<div class="box" style="background-image: url('https://www.catster.com/wp-content/uploads/2017/11/A-Siamese-cat.jpg')"></div>
<div class="box" style="background-image: url('https://r.hswstatic.com/w_907/gif/tesla-cat.jpg')"></div>
<div class="box" style="background-image: url('https://r.ddmcdn.com/s_f/o_1/cx_462/cy_245/cw_1349/ch_1349/w_720/APL/uploads/2015/06/caturday-shutterstock_149320799.jpg')"></div>
<div class="box" style="background-image: url('https://www.shelterluv.com/sites/default/files/animal_pics/464/2016/11/25/22/20161125220040.png')"></div>
<div class="box" style="background-image: url('https://r.ddmcdn.com/w_830/s_f/o_1/cx_0/cy_66/cw_288/ch_162/APL/uploads/2014/10/cat_5-1.jpg')"></div>
<div class="box" style="background-image: url('https://cdn.theatlantic.com/assets/media/img/mt/2017/06/shutterstock_319985324/lead_720_405.jpg?mod=1533691890')"></div>
</div>
CSS:
body {margin:0}
.grid-container {width:100%;}
.box {
width:20vw;
height:33.33vh;
float:left;
border:1px solid white;
background-size: cover;
background-position:center;
}
Since you are changing the background-image url in a random element, each time you are going to potentially lose a url if the other url is a copy of one of the others.
You could parse all the urls and keep them in an array and grab the urls randomly from that array instead of the elements themselves since you will be changing the elements.
var $squares = $('.box');
//create an array from all the backgroundImage values
var urls = $squares.map(function(){
return this.style.backgroundImage;
});
Then in imgFade
var square1 = $squares.eq([Math.floor(Math.random()*$squares.length)])
//get random urls from the array instead of the elements
var square1Url = urls[Math.floor(Math.random()*$squares.length)];
var square2Url = urls[Math.floor(Math.random()*$squares.length)];
Demo
var $squares = $('.box');
var urls = $squares.map(function() {
return this.style.backgroundImage;
});
function imgFade() {
var square1 = $squares.eq([Math.floor(Math.random() * $squares.length)])
var square1Url = urls[Math.floor(Math.random() * $squares.length)];
var square2Url = urls[Math.floor(Math.random() * $squares.length)];
$(square1).fadeOut(1500, function() {
$(this).css("background-image", square2Url);
$(this).fadeIn(1500);
});
timeoutId = setTimeout(imgFade, 1500);
}
imgFade();
body {
margin: 0
}
.grid-container {
width: 100%;
}
.box {
width: 20vw;
height: 33.33vh;
float: left;
border: 1px solid white;
background-size: cover;
background-position: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="grid-container">
<div class="box" style="background-image: url('https://www.catster.com/wp-content/uploads/2017/11/A-Siamese-cat.jpg')">
</div>
<div class="box" style="background-image: url('https://r.hswstatic.com/w_907/gif/tesla-cat.jpg')">
</div>
<div class="box" style="background-image: url('https://r.ddmcdn.com/s_f/o_1/cx_462/cy_245/cw_1349/ch_1349/w_720/APL/uploads/2015/06/caturday-shutterstock_149320799.jpg')">
</div>
<div class="box" style="background-image: url('https://www.shelterluv.com/sites/default/files/animal_pics/464/2016/11/25/22/20161125220040.png')">
</div>
<div class="box" style="background-image: url('https://r.ddmcdn.com/w_830/s_f/o_1/cx_0/cy_66/cw_288/ch_162/APL/uploads/2014/10/cat_5-1.jpg')">
</div>
<div class="box" style="background-image: url('https://cdn.theatlantic.com/assets/media/img/mt/2017/06/shutterstock_319985324/lead_720_405.jpg?mod=1533691890')">
</div>
</div>
Side note you dont need to do the url() replace since you are just adding it back in when setting the new background.
Also you will end up with multiple duplicates since it is random. But you won't end up just having a single url being used. If you don't want multiple duplicates, eg more than 2 duplicates at a time, you would need to write a check to see if that url has been used more than once and if so get a different one until you get one that hasn't been.
If you want no duplicates at all you would have to swap 2 backgrounds at once instead of just one at a time. This would be a bit easier code wise but does require changing two at a time.
In this one you would do as you were but add in the change to the second element as well
var square1 = $squares.eq([Math.floor(Math.random()*$squares.length)])
//modified to not select square1
var square2 = var square2 = $squares.not(square1).eq([Math.floor(Math.random() * $squares.length-1)])
var square1Url = square1.css('background-image').replace(/(url\(|\)|")/g, '');
var square2Url = square2.css('background-image').replace(/(url\(|\)|")/g, '');
$(square1).fadeOut(1500, function() {
$(this).css("background-image", "url(" + square2Url + ")");
$(this).fadeIn(1500);
});
$(square2).fadeOut(1500, function() {
$(this).css("background-image", "url(" + square1Url + ")");
$(this).fadeIn(1500);
});
You would also need to increase the timeout to 3000 so that you don't accidently trigger a new transition while one is already taking place.
var $squares = $('.box');
var urls = $squares.map(function() {
return this.style.backgroundImage;
});
function imgFade() {
var square1 = $squares.eq([Math.floor(Math.random() * $squares.length)])
//modified to make sure we dont accidently
//select square1
var square2 = $squares.not(square1).eq([Math.floor(Math.random() * $squares.length-1)])
var square1Url = square1.css('background-image');
var square2Url = square2.css('background-image');
$(square1).fadeOut(1500, function() {
$(this).css("background-image", square2Url);
$(this).fadeIn(1500);
});
$(square2).fadeOut(1500, function() {
$(this).css("background-image", square1Url)
$(this).fadeIn(1500);
});
//change timing so it doesnt get called
//in the middle of a transition
timeoutId = setTimeout(imgFade, 3000);
}
imgFade();
body {
margin: 0
}
.grid-container {
width: 100%;
}
.box {
width: 20vw;
height: 33.33vh;
float: left;
border: 1px solid white;
background-size: cover;
background-position: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="grid-container">
<div class="box" style="background-image: url('https://www.catster.com/wp-content/uploads/2017/11/A-Siamese-cat.jpg')">
</div>
<div class="box" style="background-image: url('https://r.hswstatic.com/w_907/gif/tesla-cat.jpg')">
</div>
<div class="box" style="background-image: url('https://r.ddmcdn.com/s_f/o_1/cx_462/cy_245/cw_1349/ch_1349/w_720/APL/uploads/2015/06/caturday-shutterstock_149320799.jpg')">
</div>
<div class="box" style="background-image: url('https://www.shelterluv.com/sites/default/files/animal_pics/464/2016/11/25/22/20161125220040.png')">
</div>
<div class="box" style="background-image: url('https://r.ddmcdn.com/w_830/s_f/o_1/cx_0/cy_66/cw_288/ch_162/APL/uploads/2014/10/cat_5-1.jpg')">
</div>
<div class="box" style="background-image: url('https://cdn.theatlantic.com/assets/media/img/mt/2017/06/shutterstock_319985324/lead_720_405.jpg?mod=1533691890')">
</div>
</div>

How to clone, modify (increment some elements) before appending using jQuery?

I have an element that contains multiple elements inside it, what I need is to clone the element, but on every "new" element, I need to increment an element (the object number -see my script please-)
In the script I'm adding I need (every time I click on the button) to have : Hello#1 (by default it's the first one) but the first click make : Hello#2 (and keep on top Hello#1) second click = Hello#1 Hello#2 Hello#3 ... We need to keep the oldest hellos and show the first one.
var count = 1;
$(".button").click(function(){
count += 1;
num = parseInt($(".object span").text());
$(".object span").text(count);
var cont = $(".container"),
div = cont.find(".object").eq(0).clone();
cont.append(div);
});
.object{
width:100px;
height:20px;
background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>
<div class="container">
<div class="object">
<p>
hello#<span>1</span>
</p>
</div>
</div>
You just have to change a little:
var count = 1;
$(".button").click(function() {
count += 1;
num = parseInt($(".object span").text());
var cont = $(".container"),
div = cont.find(".object").eq(0).clone();
div.find('span').text(count); // <------here you have to put the count
cont.append(div);
});
.object {
width: 100px;
height: 20px;
background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>
<div class="container">
<div class="object">
<p>
hello#<span>1</span>
</p>
</div>
</div>
and if you want to simplify this more use this:
$(".button").click(function() {
var idx = ++$('.object').length; // check for length and increment it with ++
var cont = $(".container"),
div = cont.find(".object").eq(0).clone();
div.find('span').text(idx); // <------here you have to put the count
cont.append(div);
});
.object {
width: 100px;
height: 20px;
background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>
<div class="container">
<div class="object">
<p>
hello#<span>1</span>
</p>
</div>
</div>
Use the following function, this is more modular and you can use it to update the count if you remove one of the elements
function updateCount() {
$(".object").each(function(i,v) {
$(this).find("span").text(i+1);
});
}
$(".button").click(function() {
num = parseInt($(".object span").text());
var cont = $(".container"),
div = cont.find(".object").eq(0).clone();
cont.append(div);
updateCount();
});
.object {
width: 100px;
height: 20px;
background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>
<div class="container">
<div class="object">
<p>
hello#<span>1</span>
</p>
</div>
</div>

Could help me to resolve mouse events?

<script>
var theNumOfWins;
var part;
theNumOfWins = 0;
function openWindow(){
part = partOfWindow("outlayer",theNumOfWins,"section0");
setCSS(part.css,"-1","400px","400px","#65A8E8","relative","30px","30px","initial","none");
part = partOfWindow("headerOfWindow",theNumOfWins,part.id);
setCSS(part.css,"1","400px","25px","#65A8E8","relative","0px","0px","initial","none");
part = partOfWindow("zoneOfWindowPosition",theNumOfWins,part.id);
setCSS(part.css,"1","204px","22px","transparent","absolute","192px","4px","move","1px solid red");
document.getElementById("5").innerHTML = document.getElementById(part.id).attributes[2].value;
theNumOfWins++;
}
function partOfWindow(name,theNumOfWins,parent){
var id;
var css;
var idAndCSS;
var tag;
var att;
id = name + "Id" + theNumOfWins;
css = name + "CSS";
tag = document.createElement("div");
tag.setAttribute("id",id);
tag.setAttribute("class",css);
document.getElementById(parent).appendChild(tag);
idAndCSS = {
tag: tag,
id: id,
css: css
}
return idAndCSS;
}
function setCSS(className,zIndex,width,height,backgroundColor,position,left,top,cursor,border){
var i;
var cssPart;
cssPart = document.getElementsByClassName(className);
document.getElementById("1").innerHTML = cssPart.length;
document.getElementById("2").innerHTML = cssPart[0];
document.getElementById("3").innerHTML = cssPart[1];
document.getElementById("4").innerHTML = cssPart[2];
for(i=0; i < cssPart.length; i++){
cssPart[i].style.zIndex = zIndex;
cssPart[i].style.width = width;
cssPart[i].style.height = height;
cssPart[i].style.backgroundColor = backgroundColor;
cssPart[i].style.position = position;
cssPart[i].style.left = left;
cssPart[i].style.top = top;
cssPart[i].style.cursor = cursor;
cssPart[i].style.border = border;
}
}
</script>
Hi!!! I need help!!!
I made a object of "div".
and then I added one more "div" into first "div".
second "div" is a red box. You can see it when you click the "+"mark.
But, second "div" has mouse event, and the event does not work.
I want to change mouse cursor when cursor become on the red box.
Why does not the mouse event work?
My last purpose is to make window object.
And there will be a lot of mouse events.
I already made window object similar to this one. However, it also did not work.
How can I try mouse event?
This is my full source: https://drive.google.com/file/d/0B4p8lZSEMXcqZUdacVJyVlBiUWc/view?usp=sharing
This is a CSS issue. Your problem is here:
part = partOfWindow("outlayer",theNumOfWins,"section0");
setCSS(part.css,"-1","400px","400px","#65A8E8","relative","30px","30px","initial","none");
Specifically, where you set the z-index to -1, by doing so you place the div and everything contained in it under the active layer so to speak. As such the hover event doesn't propagate to your div. change this to 1 and the cursor will behave as expected.
var theNumOfWins;
var part;
theNumOfWins = 0;
function openWindow(){
part = partOfWindow("outlayer",theNumOfWins,"section0");
setCSS(part.css,"1","400px","400px","#65A8E8","relative","30px","30px","initial","none");
part = partOfWindow("headerOfWindow",theNumOfWins,part.id);
setCSS(part.css,"1","400px","25px","#65A8E8","relative","0px","0px","initial","none");
part = partOfWindow("zoneOfWindowPosition",theNumOfWins,part.id);
setCSS(part.css,"1","204px","22px","transparent","absolute","192px","4px","pointer","1px solid red");
document.getElementById("5").innerHTML = document.getElementById(part.id).attributes[1].value;
theNumOfWins++;
}
function partOfWindow(name,theNumOfWins,parent){
var id;
var css;
var idAndCSS;
var tag;
var att;
id = name + "Id" + theNumOfWins;
css = name + "CSS";
tag = document.createElement("div");
tag.setAttribute("id",id);
tag.setAttribute("class",css);
document.getElementById(parent).appendChild(tag);
idAndCSS = {
tag: tag,
id: id,
css: css
}
return idAndCSS;
}
function setCSS(className,zIndex,width,height,backgroundColor,position,left,top,cursor,border){
var i;
var cssPart;
cssPart = document.getElementsByClassName(className);
document.getElementById("1").innerHTML = cssPart.length;
document.getElementById("2").innerHTML = cssPart[0];
document.getElementById("3").innerHTML = cssPart[1];
document.getElementById("4").innerHTML = cssPart[2];
for(i=0; i < cssPart.length; i++){
cssPart[i].style.zIndex = zIndex;
cssPart[i].style.width = width;
cssPart[i].style.height = height;
cssPart[i].style.backgroundColor = backgroundColor;
cssPart[i].style.position = position;
cssPart[i].style.left = left;
cssPart[i].style.top = top;
cssPart[i].style.cursor = cursor;
cssPart[i].style.border = border;
}
}
#buttonToOpenWindow{
width:50px;
height:20px;
border: 1px solid #DCDCDC;
margin: 2px;
position:fixed;
left:-1px;
top:0px;
}
#buttonToOpenWindow div.positionOfPlus{
width:20px;
height:20px;
position:absolute;
left:30px;
}
div.wrapOfPlus{
width:20px;
height:20px;
}
div.inside01{
width:15px;
height:5px;
background-color: #B0C4DE;
position:absolute;
left:2.5px;
top:7.5px;
}
div.inside02{
width:5px;
height:15px;
background-color: #B0C4DE;
position:absolute;
left:7.5px;
top:2.5px;
}
<section id="section0">
<div id="buttonToOpenWindow" onclick="openWindow()">
<div class="positionOfPlus">
<div class="wrapOfPlus">
<div class="inside01"></div>
<div class="inside02"></div>
</div>
</div>
</div>
</section>
<footer>
<br><br><br><br><br>
<div style="display:inline-flex;">00: <div id="0"></div></div><br>
<div style="display:inline-flex;">01: <div id="1"></div></div><br>
<div style="display:inline-flex;">02: <div id="2"></div></div><br>
<div style="display:inline-flex;">03: <div id="3"></div></div><br>
<div style="display:inline-flex;">04: <div id="4"></div></div><br>
<div style="display:inline-flex;">05: <div id="5"></div></div><br>
<div style="display:inline-flex;">06: <div id="6"></div></div><br>
<div style="display:inline-flex;">07: <div id="7"></div></div><br>
<div style="display:inline-flex;">08: <div id="8"></div></div><br>
<div style="display:inline-flex;">09: <div id="9"></div></div><br>
<div style="display:inline-flex;">10: <div id="10"></div></div><br>
<div style="display:inline-flex;">11: <div id="11"></div></div><br>
<div style="display:inline-flex;">12: <div id="12"></div></div><br>
<div style="display:inline-flex;">13: <div id="13"></div></div><br>
<div style="display:inline-flex;">14: <div id="14"></div></div><br>
<div style="display:inline-flex;">15: <div id="15"></div></div><br>
<div style="display:inline-flex;">16: <div id="16"></div></div><br>
<div style="display:inline-flex;">17: <div id="17"></div></div><br>
<div style="display:inline-flex;">18: <div id="18"></div></div><br>
<div style="display:inline-flex;">19: <div id="19"></div></div><br>
<div style="display:inline-flex;">20: <div id="20"></div></div><br>
<div style="display:inline-flex;">21: <div id="21"></div></div><br>
<div style="display:inline-flex;">22: <div id="22"></div></div><br>
<div style="display:inline-flex;">23: <div id="23"></div></div><br>
<div style="display:inline-flex;">24: <div id="24"></div></div><br>
<div style="display:inline-flex;">25: <div id="25"></div></div><br>
<div style="display:inline-flex;">26: <div id="26"></div></div><br>
<div style="display:inline-flex;">27: <div id="27"></div></div><br>
<div style="display:inline-flex;">28: <div id="28"></div></div><br>
<div style="display:inline-flex;">29: <div id="29"></div></div><br>
<div style="display:inline-flex;">30: <div id="30"></div></div><br>
<div style="display:inline-flex;">111: <div id="111"></div></div><br>
<div style="display:inline-flex;">222: <div id="222"></div></div><br>
<div style="display:inline-flex;">333: <div id="333"></div></div><br>
<div style="display:inline-flex;">444: <div id="444"></div></div><br>
<div style="display:inline-flex;">555: <div id="555"></div></div><br>
<div style="display:inline-flex;">666: <div id="666"></div></div><br>
<div style="display:inline-flex;">777: <div id="777"></div></div><br>
<div style="display:inline-flex;">888: <div id="888"></div></div><br>
<div style="display:inline-flex;">999: <div id="999"></div></div><br>
</footer>

Categories

Resources