Angular material 1 / md-virtual-repeat select scroll - javascript

What is the right way to change md-virtual-repeat's scroll to watch events from an other scroll ?
I have tried some manual triggering
And i readed this question but it is not exactly i want.
So is there a way to select a scrool to virtual-repeat container ?
EDIT 2
I need to change scrollbar of virtual repeat with scrollbar of Body
Live example
(function() {
'use strict';
var app = angular.module('MyApp', ['ngMaterial', 'ngMessages']);
app.filter('to_trusted', ['$sce', function($sce) {
return function(text) {
return $sce.trustAsHtml(text);
};
}]);
app.controller('AppCtrl', function($timeout) {
this.itemSize = 529.39;
var DynamicItems = function() {
this.loadedPages = {};
this.numItems = 0;
this.PAGE_SIZE = 50;
this.fetchNumItems_();
};
DynamicItems.prototype.getItemAtIndex = function(index) {
var pageNumber = Math.floor(index / this.PAGE_SIZE);
var page = this.loadedPages[pageNumber];
if (page) {
return page[index % this.PAGE_SIZE];
} else if (page !== null) {
this.fetchPage_(pageNumber);
}
};
DynamicItems.prototype.getLength = function() {
return this.numItems;
};
DynamicItems.prototype.fetchPage_ = function(pageNumber) {
this.loadedPages[pageNumber] = null;
$timeout(angular.noop, 300).then(angular.bind(this, function() {
this.loadedPages[pageNumber] = [];
var pageOffset = pageNumber * this.PAGE_SIZE;
//console.log(pageNumber);
for (var i = pageOffset; i < pageOffset + this.PAGE_SIZE; i++) {
var obj = {};
obj.name = 'Ad ' + i;
obj.surname = 'Soyad ' + i;
obj.age = i;
obj.image = 'http://lorempixel.com/75/75/cats?' + i;
obj.list = [];
obj.clicked = false;
obj.status = "asd";
obj.html = '' + i + '---Lorem Ipsum, dizgi ve baskı endüstrisinde kullanılan mıgır metinlerdir. Lorem Ipsum, adı bilinmeyen bir matbaacının bir hurufat numune kitabı oluşturmak üzere bir yazı galerisini alarak karıştırdığı 1500 lerden beri endüstri standardı sahte metinler olarak kullanılmıştır. Beşyüz yıl boyunca varlığını sürdürmekle kalmamış, aynı zamanda pek değişmeden elektronik dizgiye de sıçramıştır. 1960 larda Lorem Ipsum pasajları da içeren Letraset yapraklarının yayınlanması ile ve yakın zamanda Aldus PageMaker gibi Lorem Ipsum sürümleri içeren masaüstü yayıncılık yazılımları ile popüler olmuştur.' + i;
for (var j = 0; j < 1000; j++) {
obj.list.push('http://lorempixel.com/75/75/city/?' + j);
}
this.loadedPages[pageNumber].push(obj);
}
//this.setItemNum(this.numItems + this.PAGE_SIZE);
}));
};
DynamicItems.prototype.fetchNumItems_ = function() {
$timeout(angular.noop, 300).then(angular.bind(this, function() {
//console.log("fetchNumItems_");
this.numItems = 10000;
}));
};
DynamicItems.prototype.setItemNum = function(number) {
this.numItems = number;
};
this.dynamicItems = new DynamicItems();
//console.log(this.dynamicItems);
});
}());
.virtualRepeatdemoDeferredLoading #vertical-container {
width: 100%;
}
.virtualRepeatdemoDeferredLoading .repeated-item {
border-bottom: 1px solid #ddd;
box-sizing: border-box;
padding-top: 10px;
}
.virtualRepeatdemoDeferredLoading md-content {
margin: 16px;
}
.virtualRepeatdemoDeferredLoading md-virtual-repeat-container {
border: solid 1px grey;
}
.virtualRepeatdemoDeferredLoading .md-virtual-repeat-container .md-virtual-repeat-offsetter div {
padding-left: 16px;
}
.virtualRepeatdemoHorizontalUsage #horizontal-container {
height: 100px;
width: 100%;
}
.virtualRepeatdemoHorizontalUsage .repeated-item {
border-right: 1px solid #ddd;
box-sizing: border-box;
display: inline-block;
height: 84px;
padding-top: 10px;
text-align: center;
width: 100px;
}
.virtualRepeatdemoHorizontalUsage md-content {
margin: 16px;
}
.virtualRepeatdemoHorizontalUsage md-virtual-repeat-container {
border: solid 1px grey;
}
<!DOCTYPE html>
<html class=''>
<head>
<meta charset='UTF-8'>
<meta name="robots" content="noindex">
<link rel="shortcut icon" type="image/x-icon" href="//production-assets.codepen.io/assets/favicon/favicon-8ea04875e70c4b0bb41da869e81236e54394d63638a1ef12fa558a4a835f1164.ico" />
<link rel="mask-icon" type="" href="//production-assets.codepen.io/assets/favicon/logo-pin-f2d2b6d2c61838f7e76325261b7195c27224080bc099486ddd6dccb469b8e8e6.svg" color="#111" />
<link rel="canonical" href="http://codepen.io/anon/pen/OWXMXW" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic">
<link rel='stylesheet prefetch' href='https://cdn.gitcdn.link/cdn/angular/bower-material/v1.1.1/angular-material.css'>
<link rel='stylesheet prefetch' href='https://material.angularjs.org/1.1.1/docs.css'>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-route.min.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.min.js'></script>
<script src='https://cdn.gitcdn.link/cdn/angular/bower-material/v1.1.1/angular-material.js'></script>
</head>
<body>
<h1> Virtual Repeat Test </h1>
<div ng-controller="AppCtrl as ctrl" ng-cloak="" flex layout-fill layout-padding class="virtualRepeatdemoDeferredLoading" ng-app="MyApp">
<md-content layout="column" flex layout-fill>
<md-virtual-repeat-container flex layout-fill md-auto-shrink="false" layout id="vertical-container">
<div md-virtual-repeat="item in ctrl.dynamicItems" id="repeat_item" md-on-demand="true" md-item-size="ctrl.itemSize" layout-fill>
<img ng-src="{{item.image}}" class="md-avatar" alt="{{item.name}}" />
<br> Adı : {{item.name}} <br> Soyadı : {{item.surname}} <br> Yaşı : {{item.age}} <br> is Clicked : {{ item.clicked }} <br> status : {{ item.status }}
<p ng-bind-html=" item.html | to_trusted "> </p>
<h5 ng-click="item.clicked = !item.clicked; item.status = item.status + item.status; "> List Items </h5>
<md-content ng-if="item.clicked == true" class="virtualRepeatdemoHorizontalUsage" layout="column">
<md-virtual-repeat-container id="horizontal-container" md-orient-horizontal="">
<div md-virtual-repeat="picture in item.list" class="repeated-item" flex="">
<img ng-src="{{ picture }}" class="md-avatar" alt="{{ picture }}" />
</div>
</md-virtual-repeat-container>
</md-content>
<br>
</div>
</md-virtual-repeat-container>
</md-content>
</div>
</body>
</html>

If I understand your question correctly, you just want to scroll the virtual repeater div using a scrollbar somewhere else on your page? One way to do that would be to create a directive that listens to scroll event of the div you want to use as the visible scrollbar and then just scroll the other div the same percentage.
Here is one such directive. Add it to the md-virtual-repeat-container and point it to the div you want to scroll it. The divs can even be different heights.
Update
I changed the directive to fall back to the body tag if an element wasn't specified.
app = angular.module('myApp', ['ngMaterial']);
app.controller("myController", function($scope) {
$scope.items = [];
for (var i = 0; i < 5000000; i++) {
$scope.items.push(i);
}
});
app.directive("scrollFrom", function($window, $document) {
return {
scope: {
elTarget: '#scrollFrom'
},
link: function(scope, element, attrs) {
var body = $document[0].body;
angular.element(scope.elTarget || $window).bind("scroll", function() {
var percentScrolled = scope.elTarget ?
this.scrollHeight > 0 ? this.scrollTop / (this.scrollHeight - element.height()) : 0 :
body.scrollHeight > 0 ? body.scrollTop / (body.scrollHeight - element.height()) : 0;
var trgt = angular.element(element).find('.md-virtual-repeat-scroller')[0];
trgt.scrollTop = trgt.scrollHeight * percentScrolled;
});
}
};
});
#vertical-container {
height: 292px;
width: 100%;
max-width: 400px;
position: fixed;
top: 10px;
}
#vertical-container .md-virtual-repeat-scroller {
overflow: hidden;
}
.repeated-item {
border-bottom: 1px solid #ddd;
box-sizing: border-box;
height: 40px;
padding-top: 10px;
}
md-virtual-repeat-container {
border: solid 4px grey;
}
<html ng-app="myApp">
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/angular-material/1.1.4/angular-material.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-animate.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-aria.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-material/1.1.4/angular-material.min.js"></script>
</head>
<body style="height: 5000000px">
<div ng-controller="myController">
<md-virtual-repeat-container id="vertical-container" scroll-from>
<div md-virtual-repeat="item in items" class="repeated-item" flex>
{{item}}
</div>
</md-virtual-repeat-container>
</div>
</body>
</html>

Related

Image change with toggle

Been working on a home automation dashboard and I need some help. How do I get the image to change when the button is toggled ON and OFF. I have a sun svg for on and moon svg for off.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dashboard</title>
<!-- Add font from Google fonts -->
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght#300&display=swap" rel="stylesheet">
<!-- Link CSS style sheet to html document -->
<link rel="stylesheet" href="style.css">
<!-- Link JavaScript file to html document -->
<script src="mqttws31.js"></script>
<script src="dashboard.js"></script>
</head>
<body>
<div class="header">
<h1>Home Automation Dashboard</h1>
</div>
<hr>
<div id="messages"></div>
<div id="status"></div>
<hr>
<ul class="dashboard">
<ol class="b">
<li class="dashboard_item kitchen">
<img src="./moon.svg" width="40px" height="40px" alt="">
<h4>Kitchen</h4>
<p id="kitchen-light">OFF</p>
<button id="kitchen-btn">Toggle</button>
</li>
<ol class="b">
<li class="dashboard_item frontdoor" >
<img src="./door-closed.svg" width="40px" height="40px" alt="">
<h4>Front Door</h4>
<p>CLOSED</p>
</li>
</ul>
</body>
</html>
<!-- variable in js -->
var KitchenState = true;
var el = document.getElementById("kitchen-btn");
el.addEventListener('click', function() {
document.getElementById("kitchen-light").innerHTML = KitchenState ? "ON" : "OFF";
KitchenState = !KitchenState;
});
Been trying examples online with no luck so far.
Give some id attribute to the image and then change it in the same way like you are changing the innerHTML. For image you just need to change the src accordingly.
<script>
var KitchenState = true;
var el = document.getElementById("kitchen-btn");
el.addEventListener('click', function() {
document.getElementById("kitchen-light").innerHTML = KitchenState ? "ON" : "OFF";
document.getElementById('toggle-img').src = KitchenState ? './sun.svg' : './moon.svg'
KitchenState = !KitchenState;
});
</script>
<img src="./moon.svg" width="40px" id="toggle-img" height="40px" alt="">
use .setAttribute or .src
add id kitchen-icon to tag <img> icon
and try code:
var KitchenState = true;
var el = document.getElementById("kitchen-btn");
el.addEventListener('click', function() {
document.getElementById("kitchen-light").innerHTML = KitchenState ? "ON" : "OFF";
document.getElementById('kitchen-icon').src = KitchenState ? './moon.svg' : './sun.svg'
KitchenState = !KitchenState;
})
From the point of view of your question, I think you need the following code
let btnAll = document.getElementByTagName('button')
let conAll = document.getElementByClassName('content')
let btnAllLen = btnAll.length
//Create a callback function for the click event of each button
for (let i = 0; i < btnAllLen; i++) {
!(function(n) { // Register click events
btnAll[n].addEventListener('click', function() {
for (let j = 0; j < btnAlllen; j++) {
btn[j].className = ""
conAll[j].style.display = "none"
}
this.className = "active"
conAll[n].style.display = "block"
})
})(i)
}
.main {
text-align: center;
}
button:focus {
outline: none;
}
nav {
margin-top: 30px;
box-sizing: border-box;
}
button {
background: white;
border: none;
height: 36px;
line-height: 36px;
width: 80px;
text-align: center;
border: 1px solid lightgray;
border-radius: 4px;
cursor: pointer;
}
nav>button:not(:first-child) {
margin-left: 15px;
}
.active {
background: black;
color: white;
}
.content {
margin-top: 40px;
}
.content>p {
display: none;
}
<div class="main">
<nav>
<button class="active">content 1</button>
<button>content 2</button>
<button>content 3</button>
<button>content 4</button>
</nav>
<div class="content">
<p style="display: block;">content1</p>
<p>content2</p>
<p>content3</p>
<p>content4</p>
</div>
</div>

Store draggable DIV's position in HTML Table to MySQL database

I'd like to know if/how i will be able to store the position of where I move a draggable div to on the table, so when the page is reloaded, it will return to were it was left (from MySQL database).
i read some articles about that but it was all about using jquery (event, ui) with AJAX.
here's my code :
var p = document.getElementsByTagName('p');
var choice = document.getElementsByClassName('choice');
var dragItem = null;
for(var i of p){
i.addEventListener('dragstart', dragStart);
i.addEventListener('dragend', dragEnd);
}
function dragStart(){
dragItem = this;
setTimeout(()=>this.style.display = "none", 0);
}
function dragEnd(){
setTimeout(()=>this.style.display = "block", 0);
dragItem = null;
}
for(j of choice){
j.addEventListener('dragover', dragOver);
j.addEventListener('dragenter', dragEnter);
j.addEventListener('dragleave', dragLeave);
j.addEventListener('drop', Drop);
}
function Drop(){
this.append(dragItem);
}
function dragOver(e){
e.preventDefault();
this.style.border = "2px dotted cyan";
}
function dragEnter(e){
e.preventDefault();
}
function dragLeave(e){
this.style.border = "none";
}
section{
width: 1000px;
height: 360px;
margin: 100px auto;
display: flex;
justify-content: space-around;
}
h1{
text-align: center;
}
div{
width: 200px;
height: 90%;
padding: 20px;
margin: 10px;
background: #fafafa;
box-sizing: border-box;
}
p{
font-weight: bold;
border-radius: 5px;
padding: 5px;
color: white;
background: red;
}
table, th, td {
border:1px solid black;
}
button{
width: 100px;
height: 15px;
padding: 15px;
margin: 10px;
background: gray;
box-sizing: border-box;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test drag & drop </title>
</head>
<body>
<h1> it's just a test for js </h1>
<section>
<div2>
<table style="width:100%">
<tr>
<th>time</th>
<th>DIM</th>
<th>LUN</th>
</tr>
<tr>
<td>8:00 - 9:00</td>
<td><div class="choice"></div> S1-1</td>
<td><div class="choice"></div>S1-2</td>
</tr>
<tr>
<td>9:00 - 10:00</td>
<td><div class="choice"></div>S2-1</td>
<td><div class="choice"></div>S2-2</td>
</tr>
</table>
<button>save</button>
</div2>
<div class="choice">
<p draggable="true">MODULE 1</p>
<p draggable="true">MODULE 2</p>
<p draggable="true">MODULE 3</p>
<p draggable="true">MODULE 4</p>
<p draggable="true">MODULE 5</p>
</div>
</section>
</body>
</html>
This may be an overcomplicated answer. But I feel the best way to go about this is to store an array of module objects inside your javascript. Each module would have a position attribute that would need to be updated every time a module is moved. You could also use the data html attribute to store the position of the element on the element itself(https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes). Here is my code:
Javascript:
var dragItem = null;
let modules = loadDataFromServer();
//Initial UI
updateUI(modules);
function dragStart() {
console.log("Start")
dragItem = this;
setTimeout(() => this.style.display = "none", 0);
}
function dragEnd() {
console.log("End")
setTimeout(() => this.style.display = "block", 0);
dragItem = null;
}
function Drop() {
console.log("Drop")
console.log(dragItem)
this.append(dragItem);
moveModuleTo(modules.length - 1, modules[dragItem.dataset.position])
}
function dragOver(e) {
e.preventDefault();
this.style.border = "2px dotted cyan";
}
function dragEnter(e) {
e.preventDefault();
}
function dragLeave(e) {
this.style.border = "none";
}
//Added Code
function loadDataFromServer() {
//return an array of modules
return [
{
title: "Module 1",
position: 0
},
{
title: "Module 2",
position: 1
},
{
title: "Module 3",
position: 2
},
{
title: "Module 4",
position: 3
},
{
title: "Module 5",
position: 4
},
]
}
function moveModuleTo(position, module) {
if (module.position < position) {
//Module is moving down the list
console.log(position)
console.log(module.position)
for (let i = module.position; i < position; i++) {
modules[i] = modules[i + 1];
modules[i].position = i
}
} else {
//Module is moving up the list
for (let i = module.position - 1; i > position; i--) {
modules[i] = modules[i - 1]
modules[i].position = i + 1;
}
}
modules[position] = module
modules[position].position = position
console.log(modules)
//Update UI and database
updateUI(modules)
}
function updateUI(modules) {
let choice = document.getElementsByClassName('choice');
//Remove old Modules
const draggableContainer = document.getElementById("draggableContainer")
while (draggableContainer.firstChild) {
draggableContainer.removeChild(draggableContainer.lastChild)
}
//Add updated Modules
modules.forEach(item => {
console.log("yeet")
let newDraggableItem = document.createElement('p')
newDraggableItem.innerHTML = `${item.title}`
newDraggableItem.draggable = true
newDraggableItem.dataset.position = item.position
draggableContainer.appendChild(newDraggableItem);
});
//ReAdd Event listeners
var p = document.getElementsByTagName('p');
for (var i of p) {
i.addEventListener('dragstart', dragStart);
i.addEventListener('dragend', dragEnd);
}
for (j of choice) {
j.addEventListener('dragover', dragOver);
j.addEventListener('dragenter', dragEnter);
j.addEventListener('dragleave', dragLeave);
j.addEventListener('drop', Drop);
}
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="main.css">
<title>test drag & drop </title>
</head>
<body>
<h1> it's just a test for js </h1>
<section>
<div2>
<table style="width:100%">
<tr>
<th>time</th>
<th>DIM</th>
<th>LUN</th>
</tr>
<tr>
<td>8:00 - 9:00</td>
<td>
<div class="choice"></div> S1-1
</td>
<td>
<div class="choice"></div>S1-2
</td>
</tr>
<tr>
<td>9:00 - 10:00</td>
<td>
<div class="choice"></div>S2-1
</td>
<td>
<div class="choice"></div>S2-2
</td>
</tr>
</table>
<button>save</button>
</div2>
<div class="choice" id="draggableContainer"></div>
</section>
<script src="app.js"></script>
</body>
</html>
For updating a database you could make a write database call every time you move a module. Then every time the page is loaded just sort the array based on the position value. Hope this helps!

How to blur the whole body except a list item?

I wanted to create an effect where the whole body gets blurred or dimmed and only a particular list item appears clear. However when I set the z-index to the list item, it doesn't work. And when I set the z-index of the whole un-ordered list, it works but the all the list items appear clear (which I don't want).
Let me show you my html code:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ashish Toppo</title>
<link href="https://fonts.googleapis.com/css?family=Oxanium&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/style.css">
</head>
<body >
<!-- the html for the top bar starts here -->
<div class="top_bar" id="topBar">
<div class="logo_name" id="logoName">Ashish Toppo</div>
<ul class="menu">
<li class="menu_items currently_active_menuItem" id="home">home</li>
<li class="menu_items" id="about">about</li>
<li class="menu_items" id="education">education</li>
</ul>
</div>
<!-- the html for the top bar ends here -->
<!-- the html for the intro starts here -->
<div class="intro" id="intro">
<div class="profile_pic" id="profilePic">
<img id="profileImg" src="images/ashish-toppo-green.jpg" width="100%" height="100%" alt="a picture of mine">
</div>
<div class="intro_box" id="introBox">
<!-- some introduction text here -->
<center id="aboutPointer">To know more about me, go to the about section!</center>
</div>
</div>
<!-- the html for the intro ends here -->
<script src="js/uiversal.js"></script>
<script src="js/index.js"></script>
</body>
</html>
Now, the Universal javaScript file:
/* this is a reusable js file universal to all web pages */
/* Ashish Toppo */
"use strict";
function get(id_or_class){
var obj = {
element: ( document.getElementById(id_or_class) ) ? document.getElementById(id_or_class) :
( document.getElementsByClassName(id_or_class) ) ? document.getElementsByClassName(id_or_class) :
( document.querySelector(id_or_class) ) ? document.querySelector(id_or_class) :
console.error("The provided HTML element could not be found"),
html: () => { return obj.element; },
changeText: (text) => { obj.html().innerHTML = text; },
appendText: (text) => {
let appendOn = obj.html().innerHTML;
obj.html().innerHTML = appendOn + text;
},
previousDisplayMode: "block",
hide: () => {
obj.previousDisplayMode = obj.html().style.display;
obj.html().style.display = "none";
},
show: () => {
obj.html().style.display = obj.previousDisplayMode;
},
on: (event, callBack) => {
obj.html().addEventListener(event, callBack);
},
previousZIndex: 1,
focusOn: () => {
let blur = document.createElement("div");
blur.className = "theDivThatBlurs";
blur.style.width ="100vw";
blur.style.height ="100vh";
blur.style.display ="block";
blur.style.position ="fixed";
blur.style.top ="0";
blur.style.left ="0";
blur.style.zIndex ="9";
blur.style.backgroundColor ="rgba(0, 0, 0, 0.9)";
blur.innerHTML = "";
document.body.appendChild(blur);
obj.html().style.zIndex = "100";
}
}
return obj;
}
and the index.js file was as followed:
/* my css wasn't working as i wanted, so i had to fix it using js */
"use strict";
(function(d){
const active = d.getElementsByClassName("currently_active_menuItem");
active[0].style.textDecoration = "none";
})(document);
var about = get("about");
var aboutPointer = get("aboutPointer");
aboutPointer.on("click", function(){
console.log("the about pointer has been clicked");
focus(about);
});
function focus(theElement){
console.log("the focus is working");
theElement.focusOn();
}
You can use the box-shadow property to achieve the dimming effect. Quick and easy :)
Just toggle a class programmatically and it should work for any element you have.
Code
function focusAndDim() {
document.getElementById("maindiv").classList.toggle("visible");
// if you want to get more fancy ;)
document.getElementsByTagName("body")[0].classList.toggle("blur");
}
.visible {
box-shadow: 0 0 0 10000px #ccc;
/* this code below make everything else hidden */
/* box-shadow: 0 0 0 10000px #fff; */
position: relative;
}
.btn {
height: 20px;
line-height: 1.4;
border: 2px solid #999;
padding: 12px 24px;
margin-bottom: 10px;
border-radius: 2px;
cursor: pointer;
}
body {
display: flex;
align-items: center;
flex-direction: column;
justify-content: center;
height: 100vh;
}
body.blur div {
filter: blur(2px);
}
body.blur div.visible {
filter: blur(0);
}
<div class="btn" onclick="focusAndDim()" id="maindiv">Click Me</div>
<div>Other elements</div>

Fruit ninja type game in javascript

I'm trying to make a ninja fruit style game in javascript but problems are happening. I have this if statements that compare the variable "fruit" with the index of the "fruits" array. The problem is when I "eliminate" a fruit the other if statements doenst work.
That's how the game needs to work:
1 You start the game, a random name of a fruit appears for you to click on.
2 You click in the image of the fruit and it disappears, in this click another random fruit is generated.
3 An then you finish the game, that's prety much this.
So it's kind hard to explain, but its the same logic as the ninja fruit game. And I dont know if I need to use the shift function to eliminate the fruits in the array as well.
var fruits = ['Banana', 'Apple', 'Pineapple'];
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
if (fruit == fruits[0]) {
bana.onclick = function() {
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
bana.style.display = "none";
}
}
if (fruit == fruits[1]) {
app.onclick = function() {
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
app.style.display = "none";
}
}
if (fruit == fruits[2]) {
pin.onclick = function() {
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
pin.style.display = "none";
}
}
function movFruit() {
document.getElementById("info").style.display = "table";
document.getElementById("fruitAnimation").style.display = "table";
document.getElementById("insructions").style.display = "none";
var elem = document.getElementById("fruitAnimation");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
}
}
}
#fruitAnimation {
position: relative;
display: none;
margin: 0 auto;
}
.fr {
float: left;
padding: 80px;
}
#info {
display: none;
margin: 0 auto;
}
#insructions {
display: table;
margin: 0 auto;
margin-top: 200px;
border: 1px solid black;
padding: 10px;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<title>JSfruit</title>
</head>
<body>
<div id="info">
<h1>Fruit: <span id="frut"></span></h1>
</div>
<button onclick="movFruit() " style="display: table; margin: 0 auto;"><h4>Start the game</h4></button>
<div id="fruitAnimation">
<div class="fr" id="bana">
<img src="https://orig00.deviantart.net/5c87/f/2016/322/8/9/banana_pixel_art_by_fireprouf-daosk9z.png" width="60" height="60">
</div>
<div class="fr" id="app">
<img src="https://art.ngfiles.com/images/404000/404664_thexxxreaper_pixel-apple.png?f1454891997" width="60" height="60">
</div>
<div class="fr" id="pin">
<img src="https://i.pinimg.com/originals/c2/f9/e9/c2f9e9f8d332da97a836513de98f7b29.jpg" width="60" height="60">
</div>
</div>
<span id="insructions">Click in the fruits and erase them!</span>
</body>
</html>
Right now, you're only attaching handlers to the fruit images at the top level, in your if statements - but once those statements run and the main block finishes, it doesn't get run again.
You should attach handlers to all fruit images at once in the beginning, and then in the handlers, check to see the clicked fruit was valid.
If you're assigning text to an element, assign to textContent, not innerHTML; textContent is quicker, safer, and more predictable.
const fruits = ['Banana', 'Apple', 'Pineapple'];
const getRandomFruit = () => {
const randomIndex = Math.floor(Math.random() * fruits.length);
const fruit = fruits[randomIndex];
document.getElementById("frut").textContent = fruit;
fruits.splice(randomIndex, 1);
return fruit;
};
let fruitToClickOn = getRandomFruit();
bana.onclick = function() {
if (fruitToClickOn !== 'Banana') return;
bana.style.display = "none";
fruitToClickOn = getRandomFruit();
}
app.onclick = function() {
if (fruitToClickOn !== 'Apple') return;
app.style.display = "none";
fruitToClickOn = getRandomFruit();
}
pin.onclick = function() {
if (fruitToClickOn !== 'Pineapple') return;
pin.style.display = "none";
fruitToClickOn = getRandomFruit();
}
function movFruit() {
document.getElementById("info").style.display = "table";
document.getElementById("fruitAnimation").style.display = "table";
document.getElementById("insructions").style.display = "none";
var elem = document.getElementById("fruitAnimation");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
}
}
}
#fruitAnimation {
position: relative;
display: none;
margin: 0 auto;
}
.fr {
float: left;
padding: 80px;
}
#info {
display: none;
margin: 0 auto;
}
#insructions {
display: table;
margin: 0 auto;
margin-top: 200px;
border: 1px solid black;
padding: 10px;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<title>JSfruit</title>
</head>
<body>
<div id="info">
<h1>Fruit: <span id="frut"></span></h1>
</div>
<button onclick="movFruit() " style="display: table; margin: 0 auto;"><h4>Start the game</h4></button>
<div id="fruitAnimation">
<div class="fr" id="bana">
<img src="https://orig00.deviantart.net/5c87/f/2016/322/8/9/banana_pixel_art_by_fireprouf-daosk9z.png" width="60" height="60">
</div>
<div class="fr" id="app">
<img src="https://art.ngfiles.com/images/404000/404664_thexxxreaper_pixel-apple.png?f1454891997" width="60" height="60">
</div>
<div class="fr" id="pin">
<img src="https://i.pinimg.com/originals/c2/f9/e9/c2f9e9f8d332da97a836513de98f7b29.jpg" width="60" height="60">
</div>
</div>
<span id="insructions">Click in the fruits and erase them!</span>
</body>
</html>

Angular Show An Scroll not working

When I click on show5 and then goto5 it works as expected, but when I click on showngo5 its not working as expected, even though the same methods are called.
Why is showngo5 not working in this plunker
html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example51-production</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="anchorScrollOffsetExample" ng-controller="headerCtrl">
<div class="fixed-header">
<a href="" ng-click="gotoAnchor(x.i)" ng-repeat="x in ids" ng-show="x.visible">
goto{{x.i}}
</a><br/>
<a href="" ng-click="toggle(x)" ng-repeat="x in ids">
<span ng-show="x.visible">hide</span><span ng-show="!x.visible">show</span>{{x.i}}
</a><br/>
<a href="" ng-click="showngo(x)" ng-repeat="x in ids">
<span ng-show="x.visible">hide</span><span ng-show="!x.visible">showngo</span>{{x.i}}
</a>
</div>
<div id="anchor{{x.i}}" class="anchor" ng-repeat="x in ids" ng-show="x.visible">
Anchor {{x.i}} of 5
</div>
</body>
</html>
js:
(function(angular) {
'use strict';
angular.module('anchorScrollOffsetExample', [])
.run(['$anchorScroll', function($anchorScroll) {
$anchorScroll.yOffset = 100; // always scroll by 50 extra pixels
}])
.controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
function ($anchorScroll, $location, $scope) {
$scope.ids = [
{i:1,visible:true},
{i:2,visible:true},
{i:3,visible:true},
{i:4,visible:true},
{i:5,visible:false}
];
$scope.toggle = function(x) {
if(x.visible){
x.visible=false;
}else{
x.visible=true;
}
};
$scope.showngo = function(x) {
$scope.toggle(x);
$scope.gotoAnchor(x);
};
$scope.gotoAnchor = function(x) {
var newHash = 'anchor' + x;
if ($location.hash() !== newHash) {
$location.hash('anchor' + x);
} else {
$anchorScroll();
}
};
}
]);
})(window.angular);
css:
body {
padding-top: 100px;
}
.anchor {
background-color: DarkOrchid;
margin: 2px;
padding: 10px 10px 300px 10px;
}
.fixed-header {
background-color: rgba(0, 0, 0, 0.2);
height: 100px;
position: fixed;
top: 0; left: 0; right: 0;
}
.fixed-header > a {
display: inline-block;
margin: 5px 15px;
}
change this code on line #25 JS file
$scope.gotoAnchor(x.i);
The problem is you try to passing x object into gotoAnchor function rather then a number.
Update showngo function by below code. issue in your code is that when you call $scope.gotoAnchor(x); inside showngo method it will scroll to anchor[Object,Object] instead of scrolling anchor5 because whole object is passed inside x.
$scope.showngo = function(x) {
$scope.toggle(x);
$scope.gotoAnchor(x.i);
};

Categories