I'm trying to make a simple game where
you start with 9 circles
when you click on a circle with a thicker border it's going to increment a score and cause new circles to be drawn randomly.
I've already worked on counting stuff but I have a problem, because wherever you click (I mean whatever div) it sums up points. I don't have an idea about how to deactivate div's which do not have a thicker border.
Please tell if this is a good programming approach.
HTML
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-2">
<h1> Wyniki </h1>
<p> Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet. </p>
</div>
<div class="col-md-8">
<h1> Gra </h1>
<div class="wynik">
<h2> Rezultat </h2>
<p id="zliczenie"> </p>
</div>
<div class="points"> </div>
</div>
<div class="col-md-2">
<h1> Profil </h1>
<p> Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet. </p>
</div>
</div>
</div>
</body>
CSS
body {
background-color: #ecf0f1;
margin : 2% 2%;
}
.wynik{
border : solid 1px blue;
}
.point {
width : 100px;
height : 100px;
border : solid 1px #000;
border-radius : 100%;
text-align : center;
cursor : pointer;
float : left;
margin : 20px;
}
.point:hover {
color : red;
border-radius : 0%;
}
.points{
width : calc(140px * 3);
margin : 5px auto;
}
JS
window.onload = start;
function start()
{
var div_value = "";
for (i = 0; i < 9; i++)
{
var element = "div_number" + i;
div_value = div_value + '<div class="point" id="'+element+'" onclick="c('+i+')"> Klik </div>';
if((i+1)%3 == 0)
{
div_value = div_value + '<div style="clear:both;"> </div>';
}
}
document.getElementsByClassName("points")[0].innerHTML = div_value;
esthetic();
random_show();
}
// IT SHOWS 1 RANDOM DIV TO START THE GAME
function random_show() {
var a = Math.floor((Math.random() * 8));
var x = document.getElementById("div_number" + a).style.border="10px dotted";
}
var liczby = [];
// IT DROWN LOTS AND COUNT THE SCORE
function c(i)
{
var a = Math.floor((Math.random() * 8));
this.i = a;
var z = document.getElementById("div_number" + i);
var y = document.getElementById("div_number" + a);
if(y.style.border = "10px dotted") {
z.style.border ="5px dotted";
liczby.push(i);
} else {
y.style.border="8px solid";
}
var x = document.getElementById("zliczenie").innerHTML = liczby.length;
}
// IT GIVES EVERY DIV INITIAL style.border
function esthetic()
{
var x = document.getElementsByClassName("point");
for (i = 0; i < 9; i++)
{
x[i].style.border = "5px dotted";
}
}
Thanks a lot for any hints one more time!
You can store the current bordered div number in a variable, and each time the click function is called, you can check if the same div number triggered this function call.
Here is your modified code that does this:
window.onload = start;
function start() {
var div_value = "";
for (i = 0; i < 9; i++) {
var element = "div_number" + i;
div_value = div_value + '<div class="point" id="' + element + '" onclick="c(' + i + ')"> Klik </div>';
if ((i + 1) % 3 == 0) {
div_value = div_value + '<div style="clear:both;"> </div>';
}
}
document.getElementsByClassName("points")[0].innerHTML = div_value;
esthetic();
random_show();
}
currDiv = 0;
// IT SHOWS 1 RANDOM DIV TO START THE GAME
function random_show() {
var a = Math.floor((Math.random() * 8));
currDiv = a; // assign current bordered div
var x = document.getElementById("div_number" + a).style.border = "10px dotted";
}
var liczby = [];
// IT DROWN LOTS AND COUNT THE SCORE
function c(i) {
if (parseInt(i) == currDiv) { // check if the current div clicked is the bordered div
var a = Math.floor((Math.random() * 8));
this.i = a;
var z = document.getElementById("div_number" + i);
var y = document.getElementById("div_number" + a);
currDiv = a; // change it to the current bordered div
if (y.style.border = "10px dotted") {
z.style.border = "5px dotted";
liczby.push(i);
} else {
y.style.border = "8px solid";
}
var x = document.getElementById("zliczenie").innerHTML = liczby.length;
}
}
// IT GIVES EVERY DIV INITIAL style.border
function esthetic() {
var x = document.getElementsByClassName("point");
for (i = 0; i < 9; i++) {
x[i].style.border = "5px dotted";
}
}
body {
background-color: #ecf0f1;
margin: 2% 2%;
}
.wynik {
border: solid 1px blue;
}
.point {
width: 100px;
height: 100px;
border: solid 1px #000;
border-radius: 100%;
text-align: center;
cursor: pointer;
float: left;
margin: 20px;
}
.point:hover {
color: red;
border-radius: 0%;
}
.points {
width: calc(140px * 3);
margin: 5px auto;
}
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-2">
<h1> Wyniki </h1>
<p>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.</p>
</div>
<div class="col-md-8">
<h1> Gra </h1>
<div class="wynik">
<h2> Rezultat </h2>
<p id="zliczenie"></p>
</div>
<div class="points"></div>
</div>
<div class="col-md-2">
<h1> Profil </h1>
<p>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.</p>
</div>
</div>
</div>
</body>
Hope it helps!
It is always good practice to keep the styling in .css file and html tags in .html file and the code in .js file.
Also for checking if a particular style is there on an element, you should just check if the element has a particular class in its classlist. Refer: https://developer.mozilla.org/en/docs/Web/API/Element/classList
Create new classes in your .css as:
.boldCircle {
border: 10px dotted;
}
And in your code just do:
if(y.classlist.contains("boldCircle")) {
// Do what you want
}
Another thing that I would like to point out is the equality in if condition. You should use '==' instead of '='. '=' is assignment operator and evaluates to true always.
if (y.style.border == "10px dotted") {
// Do what you want
}
Building on #DeepakKumar recommendation, I would also think about using a class to flag an element as the active target. Your click event handler can then check for it and increment points/manage your array as needed.
I also simplified the code a bit to better format it for this sandbox.
// =====================
// Initialize the game
// =====================
function start() {
var divTemplate = '<div id="%1%" class="point" data-index="%2%" onclick="c(event)"> Klik </div>';
var clearTemplate = '<div style="clear:both;"> </div>';
var elPoints = document.getElementsByClassName("points")[0];
var div_value = "";
for (i = 0; i < 9; i++) {
div_value += divTemplate
.replace("%1%", "div_number" + i)
.replace("%2%", i);
if ((i + 1) % 3 == 0) { div_value += clearTemplate; }
}
elPoints.innerHTML = div_value;
liczby = [];
random_show();
}
// =====================
// =====================
// Set one div as the target
// =====================
function random_show() {
var a = Math.floor((Math.random() * 8));
var elCurrentTarget = document.querySelector(".point.target");
var elNewTarget = document.getElementById("div_number" + a);
if (elCurrentTarget) { elCurrentTarget.classList.remove("target"); }
elNewTarget.classList.add("target");
}
// =====================
// =====================
// If the target div was clicked increment the score
// reset the board.
// =====================
function c(event) {
var elTarget = event.target;
var elScore = document.getElementById("zliczenie");
if (elTarget.classList.contains("target")) {
liczby.push(elTarget.getAttribute("data-index"));
elScore.innerHTML = liczby.length;
}
random_show();
}
// =====================
var liczby = [];
window.onload = start;
.wynik {
border: solid 1px blue;
}
.points {
width: calc(140px * 3);
margin: 5px auto;
}
.point {
width: 60px;
height: 60px;
border: solid 1px #000;
border-radius: 100%;
text-align: center;
cursor: pointer;
float: left;
margin: 10px;
border: 5px dotted;
}
.point.target {
border: 10px dotted;
}
.point:hover {
color: red;
border-radius: 0%;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha256-916EbMg70RQy9LHiGkXzG8hSg9EdNy97GazNG/aiY1w=" crossorigin="anonymous" />
<div class="container-fluid">
<div class="row">
<div class="wynik">
<span>Rezultat: </span><span id="zliczenie"></span>
</div>
<div class="points"></div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha256-U5ZEeKfGNOja007MMD3YBI0A3OSZOQbeG6z2f2Y0hu8=" crossorigin="anonymous"></script>
The following code means "score + 1 if you clicked the thick circle, score - 1 otherwise" :
score += i == winning ? +1 : -1;
See conditional operator for details.
A post about randomness : https://stackoverflow.com/a/32395535/1636522.
var boardEl = document.getElementById("board"),
scoreEl = document.getElementById("score"),
indexOf = Array.prototype.indexOf,
winning = 0,
score = 0;
scoreEl.textContent = "( " + score + " )";
boardEl.innerHTML = new Array(10).join("");
boardEl.childNodes[winning].setAttribute("class", "winning");
boardEl.onclick = function (ev) {
var i, rdm, winningEl;
ev.preventDefault();
if (ev.target.parentNode == boardEl) {
i = indexOf.call(boardEl.childNodes, ev.target);
score += i == winning ? +1 : -1;
winningEl = boardEl.childNodes[winning];
winningEl.setAttribute("class", "");
rdm = Math.floor(Math.random() * 8);
winning = rdm >= winning ? rdm + 1 : rdm;
winningEl = boardEl.childNodes[winning];
winningEl.setAttribute("class", "winning");
scoreEl.textContent = "( " + score + " )";
}
};
#board, #score {
display: inline-block;
vertical-align: middle;
}
#board {
width: 150px;
}
#score {
font: bold 32px Arial;
color: #666;
}
#board a {
vertical-align: top;
display: inline-block;
border: 5px dashed #666;
border-radius: 50%;
height: 30px;
width: 30px;
margin: 5px;
}
#board a.winning {
border-width: 10px;
height: 20px;
width: 20px;
}
#board a:hover {
border-color: black;
}
<div id="board"></div>
<div id="score"></div>
Related
I have a 2x2 grid and i'm trying to set a min-height based on if one of them is larger in height than the other. so that left and right will have the same height. I'm looking for CSS here just js.
I have this on a resize event.
const updateSize = () => {
const group = Array.from(document.querySelectorAll('.items'));
const heights = group.map(item => item.clientHeight);
group.forEach((item, index) => {
const count = index % 2;
if (count === 1) {
const h = heights[index - 1];
item.style.minHeight = `${h}px`;
}
});
};
The above works but the only problem is it's only checking the last item and won't work if the current item is larger in height than the first.
I need a way to check against the last and update the corresponding items.
Here is the layout. Note that the gray boxes at the bottom are misaligned:
body {
background: #20262E;
font-family: Helvetica;
width: 100%;
}
.component {
width: 100%;
}
.grid {
display: grid;
width: 100%;
grid-template-columns: repeat(2, 50%);
}
.item {
border: 1px solid green;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.images-collection {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.image {
width: 100px;
height: 100px;
border: 1px solid white;
}
.textWrapper {
border: 1px solid blue;
display: flex;
justify-content: center;
align-content: flex-end;
background-color: gray;
}
.text {
text-align: center;
color: white;
width: 300px;
}
<div class="component">
<div class="grid">
<div class="item">
<div class="images-collection">
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
</div>
<div class="textWrapper">
<div class="text">
<p>This is my title</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor. Lorem ipsum dolor sit amet,</p>
</div>
</div>
</div>
<div class="item">
<div class="images-collection">
<div class="image"></div>
</div>
<div class="textWrapper">
<div class="text">
<p>This is my title</p>
<p>Lorem ipsum dolor sit amet.</p>
</div>
</div>
</div>
</div>
</div>
try:
const updateSize = () => {
const Allitem = document.querySelectorAll('.item')
, MaxHeight = 0
Allitem.forEach(item=>{ item.style.minHeight = '' }) // remove values
MaxHeight = Array.from(Allitem).reduce((a,c)=>a<c.clientHeight?c.clientHeight:a,0)
Allitem.forEach(item=>{ item.style.minHeight = `${MaxHeight}px` })
}
For the case where only the cells of the same line must be of the same height:
const updateSize = () => {
const Allitems = document.querySelectorAll('.item')
let ItemsOnLine = []
, topPos = -99999
, MaxHeight = 0
const setHeights = h => ItemsOnLine.forEach(item=>{ item.style.minHeight = `${h}px` })
Allitems.forEach(item=>{ item.style.minHeight = '' }) // remove values
Allitems.forEach(item=>{
if (item.offsetTop != topPos)
{
setHeights(MaxHeight)
MaxHeight = 0
ItemsOnLine.length = 0
topPos = item.offsetTop
}
MaxHeight = Math.max(MaxHeight, item.clientHeight )
ItemsOnLine.push( item )
})
setHeights(MaxHeight)
}
I have a list:
<ol class="list" id="drag-list">
<li data-itemid="01" draggable="true">
<span class="dragger"></span>
<span>01 - Lorem ipsum dolor sit amet.</span>
</li>
<li data-itemid="02" draggable="true">
<span class="dragger"></span>
<span>02 - Lorem ipsum dolor.</span>
</li>
<li data-itemid="03" draggable="true">
<span class="dragger"></span>
<span>03 - Lorem ipsum dolor sit amet, consectetur adipisicing elit.</span>
</li>
<li data-itemid="04" draggable="true">
<span class="dragger"></span>
<span>04 - Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet aliquam dolore totam, labore, voluptate delectus?</span>
</li>
<li data-itemid="05" draggable="true">
<span class="dragger"></span>
<span>05 - Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quo, soluta.</span>
</li>
</ol>
Now I need to reorder the LI's members using the HTML5 drag 'n drop.
My issue is that releasing in the new position never happens. I even tried to use this example but it did not work for me:
https://html.spec.whatwg.org/multipage/dnd.html#event-drag
Here I leave you a jsfiddle with my full working (and wrong) code. May you help me please.
https://jsfiddle.net/junihh/vrg7oj2w/
you can try this
var dragSrcEl = null;
function handleDragStart(e) {
// Target (this) element is the source node.
dragSrcEl = this;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', this.outerHTML);
this.classList.add('dragElem');
}
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop.
}
this.classList.add('over');
e.dataTransfer.dropEffect = 'move'; // See the section on the DataTransfer object.
return false;
}
function handleDragEnter(e) {
// this / e.target is the current hover target.
}
function handleDragLeave(e) {
this.classList.remove('over');
}
function handleDrop(e) {
if (e.stopPropagation) {
e.stopPropagation();
}
if (dragSrcEl != this) {
this.parentNode.removeChild(dragSrcEl);
var dropHTML = e.dataTransfer.getData('text/html');
this.insertAdjacentHTML('beforebegin',dropHTML);
var dropElem = this.previousSibling;
addDnDHandlers(dropElem);
}
this.classList.remove('over');
return false;
}
function handleDragEnd(e) {
this.classList.remove('over');
}
function addDnDHandlers(elem) {
elem.addEventListener('dragstart', handleDragStart, false);
elem.addEventListener('dragenter', handleDragEnter, false)
elem.addEventListener('dragover', handleDragOver, false);
elem.addEventListener('dragleave', handleDragLeave, false);
elem.addEventListener('drop', handleDrop, false);
elem.addEventListener('dragend', handleDragEnd, false);
}
var cols = document.querySelectorAll('#drag-list li');
[].forEach.call(cols, addDnDHandlers);
* {
margin: 0;
padding: 0;
border: 0;
vertical-align: baseline;
-webkit-tap-highlight-color: rgba(0,0,0,0);
list-style: none;
outline: 0;
}
html {
position: relative;
width: 100%;
height: 100%;
background-color: #FFF;
font: normal 18px/100% Helvetica,Arial,sans-serif;
color: #666;
}
.transitions, a, .page {
-webkit-transition: all 0.3s ease-out;
-moz-transition: all 0.3s ease-out;
-ms-transition: all 0.3s ease-out;
transition: all 0.3s ease-out;
}
a {
color: #000;
text-decoration: underline;
}
a:hover { text-decoration: none; }
.page {
max-width: 750px;
min-width: 230px;
margin: 25px auto;
padding: 0 25px;
}
.list li {
position: relative;
overflow: hidden;
margin-bottom: 5px;
border: 1px solid #DDD;
cursor: move; //effect drag and drop
}
.list span {
display: block;
}
.list span:nth-child(1) {
position: absolute;
left: 0;
top: 0;
height: 100%;
width: 25px;
background-color: #EEE;
}
.list span:nth-child(2) {
padding: 10px 10px 10px 40px;
line-height: 120%;
}
<ol class="list" id="drag-list">
<li draggable="true">
<span class="dragger"></span>
<span>01 - Lorem ipsum dolor sit amet.</span>
</li>
<li draggable="true">
<span class="dragger"></span>
<span>02 - Lorem ipsum dolor.</span>
</li>
<li draggable="true">
<span class="dragger"></span>
<span>03 - Lorem ipsum dolor sit amet, consectetur adipisicing elit.</span>
</li>
<li draggable="true">
<span class="dragger"></span>
<span>04 - Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet aliquam dolore totam, labore, voluptate delectus?</span>
</li>
<li draggable="true">
<span class="dragger"></span>
<span>05 - Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quo, soluta.</span>
</li>
</ol>
Add the dragover and drop events to the list.
Reference:
https://developer.mozilla.org/en-US/docs/Web/Events/drop
I have been trying to run an overflow check if I hover on a div. But I use jQuery for the hover function and in the next function there's just simple Javascript. It's not working because I assume one can't use the if then function inside a jQuery function... but then I need the action that if I hover over the div the if then function should be executed. Can someone help me please? =)
So it's jQuery (hover) -> JS (check overflow) -> jQuery (add to div (here: "...read more..."))
HTML:
<div class="hover_cap">
<div class="hcd">
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
</div>
</div>
CSS:
.hover_cap {
width:150px;
max-height: 17.5ex;
border: 1px solid red;
}
.hcd {
line-height:2.5ex;
max-height:12.5ex;
margin: 10px;
border: 1px solid green;
overflow: hidden;
}
.readmore {
padding: 0px 10px 10px 10px;
}
JS:
$('.hover_cap').hover(
if (function checkOverflow(hcd) {
var curOverflow = hcd.style.overflow;
if (!curOverflow || curOverflow === "hidden") hcd.style.overflow = "visible";
var isOverflowing = hcd.clientWidth < hcd.scrollWidth || hcd.clientHeight < hcd.scrollHeight;
hcd.style.overflow = curOverflow;
return isOverflowing;
}) {
function() {
$(this).append($('<a>...read more...</a>'));
},
function() {
$(this).find("a:last").remove();
}
}
}
Here is a snippet for you:
When you hover the outer div, if the inner div's text is overflowed append a 'readmore' button to the outer div.
When you unhover the outer div, if there is an appended 'readmore' button remove it.
function isOverflowed(element){
return element.scrollHeight > element.clientHeight || element.scrollWidth > element.clientWidth;
}
$(document).ready(function(){
$('.hover_cap').hover(function(){
var $this = $(this);
var $textContainer = $this.find('.hcd');
$textContainer.css('overflow','auto');
var isOverflowing = isOverflowed($textContainer[0]);
$textContainer.css('overflow','hidden');
if(isOverflowing) {
$this.append($('<a>...read more...</a>'));
}
}, function(){
var $this = $(this);
var lastA = $this.find("a:last");
if(lastA) {
lastA.remove();
}
})
})
.hover_cap {
width:150px;
max-height: 17.5ex;
border: 1px solid red;
}
.hcd {
line-height:2.5ex;
max-height:12.5ex;
margin: 10px;
border: 1px solid green;
overflow: hidden;
}
.readmore {
padding: 0px 10px 10px 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hover_cap">
<div class="hcd">
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
</div>
</div>
<br/>
<br/>
<div class="hover_cap">
<div class="hcd">
Short text, no overflow
</div>
</div>
Can you please let me know if it is possible to detect the 40% in the Middle of a Div Using jQuery for example in following example I need to enable the mousemove() only on 30% left side or 30% of the right side of the center.
$('#box-wrap').mousemove(function(e){
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
console.log("X: " + x + " Y: " + y);
});
html, body{
width:100%;
height:100;
}
#box-wrap{
height:400px;
width:100%;
background:yellow;
}
<div id="box-wrap"></div>
Thanks
Add just two transparent divs as an overlay on the left and right and have the mouse move events only on those. I just added a red border to make them visible:
$('.sensor').mousemove(function(e){
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
console.log("X: " + x + " Y: " + y);
});
html, body{
width:100%;
height:100;
}
#box-wrap{
height:400px;
width:100%;
background:yellow;
}
.sensor {
width:30%;
height: 100%;
border: 1px solid red;
background-color: transparent;
cursor: pointer;
}
.left {
position:absolute;
left: 0px;
top: 0px;
}
.right{
position:absolute;
right: 0px;
top: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="box-wrap">
<div class="left sensor"></div>
<div class="right sensor"></div>
Lorem Ipsum dolor sit anem Lorem Ipsum dolor sit anem Lorem Ipsum dolor sit anem Lorem Ipsum dolor sit anem Lorem Ipsum dolor sit anem Lorem Ipsum dolor sit anem Lorem Ipsum dolor sit anem Lorem Ipsum dolor sit anem Lorem Ipsum dolor sit anem Lorem Ipsum dolor sit anem Lorem Ipsum dolor sit anem Lorem Ipsum dolor sit anem Lorem Ipsum dolor sit anem Lorem Ipsum dolor sit anem ....
</div>
How about adding two child divs and calling .mousemove() on them instead?
<div id="box-wrap">
<div id="left_30"></div>
<div id="right_30"></div>
</div>
#left_30 {
position: absolute;
width: 30%;
height: 100%;
}
#right_30 {
position: absolute;
width: 30%;
height: 100%;
right: 0px;
}
Check out this working fiddle: https://jsfiddle.net/qeaxu9c9/2/
Try this:
$('#box-wrap').mousemove(function(e){
var t = $(this), w = t.height(), h = t.width(), os = t.offset();
var x = e.pageX - os.left, y = e.pageY - os.top;
console.log("X: " + x + " Y: " + y);
if(x >= w * 0.3 && x <= w * 0.7 && y >= h * 0.3 && y <= h * 0.7){
console.log('Inner 40%');
}
});
I would like to know how could I make my div that contains text fade in from bottom to top when scrolling down the page? i will be grateful for your help. Here is my Code:
var $text = $('.textBlock');
$(window).on('scroll', function(event, element) {
$text.each(function(event, element) {
if ($(this).visible()) {
$(this).children('p').stop().fadeIn();
} else {
$(this).siblings('.textBlock p').stop().fadeOut();
}
});
});
.textBlock {
text-align: center;
width: 100%;
height: 118px;
float: left;
display: block;
}
.textBlock p {
font-size: 24px;
padding: 30px 0;
line-height: 25px;
letter-spacing: 0.1em;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="blockOne" class="textBlock">
<p>Lorem ipsum dolor sit Amet, consectetuer adipiscing.</p>
</div>
<div id="blockTwo" class="textBlock">
<p>Lorem ipsum dolor sit Amet, consectetuer adipiscing.</p>
</div>
<div id="blockThree" class="textBlock">
<p>Lorem ipsum dolor sit Amet, consectetuer adipiscing.</p>
</div>
You need to use a timer function for this. Check this out:
$(function () {
$(".textBlock").hide();
$("#blockOne").show();
$(window).scroll(function () {
numTextBlocks = $(".textBlock").length;
$(".textBlock:visible").fadeOut(400, function () {
console.log(".textBlock:nth-child(" + ($(window).scrollTop() * 10) % numTextBlocks + ")");
$(".textBlock:nth-child(" + ($(window).scrollTop() * 10) % numTextBlocks + ")").fadeIn(400);
});
});
});
html, body {
height: 150%;
}
.textBlock {
position: fixed;
text-align: center;
width: 100%;
height: 118px;
}
.textBlock p {
font-size: 24px;
padding: 30px 0;
line-height: 25px;
letter-spacing: 0.1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="blockOne" class="textBlock">
<p>One Lorem ipsum dolor sit Amet, consectetuer adipiscing.</p>
</div>
<div id="blockTwo" class="textBlock">
<p>Two Lorem ipsum dolor sit Amet, consectetuer adipiscing.</p>
</div>
<div id="blockThree" class="textBlock">
<p>Three Lorem ipsum dolor sit Amet, consectetuer adipiscing.</p>
</div>
This is what I used:
$(document).on("mousewheel", function () {
$(".textBlock:not(:visible)").first().fadeIn("slow")
});
Here is the JSFiddle demo
Let me know if this code works with you.
Fiddle
$(window).on("load",function() {
function fade() {
$('.fade').each(function() {
/* Check the location of each desired element */
var objectBottom = $(this).offset().top + $(this).outerHeight();
var windowBottom = $(window).scrollTop() + $(window).innerHeight();
/* If the object is completely visible in the window, fade it in */
if (objectBottom < windowBottom) { //object comes into view (scrolling down)
if ($(this).css('opacity')==0) {$(this).fadeTo(500,1);}
} else { //object goes out of view (scrolling up)
if ($(this).css('opacity')==1) {$(this).fadeTo(500,0);}
}
});
}
fade(); //Fade in completely visible elements during page-load
$(window).scroll(function() {fade();}); //Fade in elements during scroll
});