How to show a custom message based on the password strength - javascript

Hi I have the following piece of code that basically checking the strength of the password and showing a div with colors based on the strength. Like a strength meter. How can I mutate the content of the div based on the strength of the password, like if the password is weak, color change to red and content says "Weak passwrd!!", if the password is moderate then content should be "Moderate password" etc. Also I would like to add a check box in the divs so if the condition is met then the color of the check box shud change to green if not then red. etc.
My codes:
HTML
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8" />
<title>My AngularJS App</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body ng-controller="stageController">
<form name="myForm" novalidate>
<label for="pw">Type a password</label><br/>
<input type="password" ng-model="pw" name="pw" id="pw" />
<li id="strength" check-strength="pw"></li>
</form>
</body>
CSS:
input.ng-pristine + ul#strength {
display:none;
}
ul#strength {
display:inline;
list-style:none;
margin:0;
margin-left:15px;
padding:0;
vertical-align:2px;
}
.point:last {
margin:0 !important;
}
.point {
background:#DDD;
border-radius:2px;
display:inline-block;
height:5px;
margin-right:1px;
width:20px;
}
#footer {
position:fixed;
bottom:5px;
}
AngularJS:
'use strict';
angular.module('myApp', ['myApp.directives']);
/* Controllers */
function stageController($scope) {
$scope.pw = '';
}
/* Directives */
angular.module('myApp.directives', []).
directive('checkStrength', function () {
return {
replace: false,
restrict: 'EACM',
link: function (scope, iElement, iAttrs) {
var strength = {
colors: ['#F00', '#F90', '#FF0', '#9F0', '#0F0'],
mesureStrength: function (p) {
var _force = 0;
var _regex = /[$-/:-?{-~!"^_`\[\]]/g;
var _lowerLetters = /[a-z]+/.test(p);
var _upperLetters = /[A-Z]+/.test(p);
var _numbers = /[0-9]+/.test(p);
var _symbols = _regex.test(p);
var _flags = [_lowerLetters, _upperLetters, _numbers, _symbols];
var _passedMatches = $.grep(_flags, function (el) { return el === true; }).length;
_force += 2 * p.length + ((p.length >= 10) ? 1 : 0);
_force += _passedMatches * 10;
// penality (short password)
_force = (p.length <= 6) ? Math.min(_force, 10) : _force;
// penality (poor variety of characters)
_force = (_passedMatches == 1) ? Math.min(_force, 10) : _force;
_force = (_passedMatches == 2) ? Math.min(_force, 20) : _force;
_force = (_passedMatches == 3) ? Math.min(_force, 40) : _force;
return _force;
},
getColor: function (s) {
var idx = 0;
if (s <= 10) { idx = 0; }
else if (s <= 20) { idx = 1; }
else if (s <= 30) { idx = 2; }
else if (s <= 40) { idx = 3; }
else { idx = 4; }
return { idx: idx + 1, col: this.colors[idx] };
}
};
scope.$watch(iAttrs.checkStrength, function () {
if (scope.pw === '') {
iElement.css({ "display": "none" });
} else {
var c = strength.getColor(strength.mesureStrength(scope.pw));
iElement.css({ "display": "inline" });
iElement.children('div')
.css({ "background": "#DDD" })
.slice(0, c.idx)
.css({ "background": c.col });
}
});
},
template: '<div class="alert alert-success"><strong>Success!</strong> Indicates a successful or positive action.</div>'
};
});

I found some code related your post, this may help you a lot
http://codepen.io/yukulele/pen/xbRpRa
var app = angular.module('app',[]);
app.controller('ctrl', function($scope){
$scope.pass="abc123456";
$scope.v=function(){
return test($scope.pass);
};
});
function test(pass){
if(pass == null)
return -1;
var s = 0;
if(pass.length<6)
return 0;
if( /[0-9]/.test( pass ) )
s++;
if( /[a-z]/.test( pass ) )
s++;
if( /[A-Z]/.test( pass ) )
s++;
if( /[^A-Z-0-9]/i.test( pass ) )
s++;
return s;
}
html{
font-size: 24px;
text-align: center;
margin: 30px;
background-color: #777;
}
label{
display: block;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<label>
password:
<input
autofocus
type="text"
ng-model="pass"/>
</label>
<label>
{{v()}}
<span ng-if="v() < 2">Weak passwrd!!</span>
<span ng-if="v() > 3">Strong password</span>
</label>
</div>

Related

Iframe is not working on my website while working on local

<iframe class="metaframe rptss" src="//fileru.net/iframe.php?v=089d20963d577068d193e23819b04652" frameborder="0" scrolling="no" allow="autoplay; encrypted-media" allowfullscreen=""></iframe>
Hello people,
I really need help. So the iframe code you see above is working perfectly on my localhost server and i can watch it without problem but when i use this same embed link on my real server it doesn't work, it just shows a black screen instead of playing button. I am trying to figure it out for days but i couldn't find a solution. I got the embed link from this website(https://720p-izle.com/izle/altyazi/modo-aviao.html) and it works there perfectly as well but it doesn't work when i add it to my own website while working on localhost.
NOTE: You might see "this video is removed because of copyright(in Turkish)", when you open the embed link. It is because this embed link just opening it in certain IP(Turkish IP) as i guess. So this embed links is working for me but only problem is that i can see video when i click, when i add my localhost or when i go to the website where i took the link from but it doesn't work when i added it to my own website.
I was trying and searching so many things but i couldn't figure it out. So i also add #document as well and it gives some clue about the solution when i look but i don't have enough knowledge to understand it and fix the problem.
Another thing is that i also use some tools like(https://www.w3schools.com/tryit/tryit.asp?filename=tryhtml_default) to see if problem is just because of my hosting and video is also not working on this tool as well.
I tried small things as well such as adding https://fileru...... or similar things and change iframe code but still it doesn't work. As i say before i saw some information about video working on documentation but i don't have enough coding knowledge to understand it.
Please help me because i am searching for the solution for days and i couldn't find anything.
<!DOCTYPE html><html lang="tr"><head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<title>Video Player</title>
<meta name="referrer" content="no-referrer"> <script type="text/javascript" async="" src="https://www.google-analytics.com/analytics.js"></script><script>
function checkScreen() {
if (window.outerHeight > 1 && window.outerWidth > 1) {
if (window.outerHeight < 200 && window.outerWidth < 300) {
window.location.href = 'about:blank';
}
} else {
setTimeout(function() {
checkScreen();
}, 2);
}
}
checkScreen();
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jwplayer.com/libraries/wr6i4gal.js"></script>
</head>
<body>
<div id="Player"></div>
<div id="icon-forward-desktop" class="jw-icon jw-icon-inline jw-button-color jw-reset jw-icon-rewind" role="button" tabindex="0" aria-label="10 Saniye İleri Sar">
<svg xmlns="http://www.w3.org/2000/svg" class="jw-svg-icon jw-svg-icon-rewind" viewBox="0 0 240 240" focusable="false">
<path d="M193.14,131.08a21.57,21.57,0,0,0-17.7-10.6,21.58,21.58,0,0,0-17.7,10.6,44.77,44.77,0,0,0,0,46.3,21.63,21.63,0,0,0,17.7,10.6,21.61,21.61,0,0,0,17.7-10.6A44.77,44.77,0,0,0,193.14,131.08Zm-17.7,47.2c-7.8,0-14.4-11-14.4-24.1s6.6-24.1,14.4-24.1,14.4,11,14.4,24.1S183.34,178.28,175.44,178.28ZM132,188V137l-4.8,4.8-6.8-6.8,13-13a4.8,4.8,0,0,1,8.2,3.4v62.7ZM30.89,52.88H161V33.58c0-5.3,3.6-7.2,8-4.3l41.8,27.9a5.8,5.8,0,0,1,2.7,2.7,6,6,0,0,1-2.7,8L169,95.78c-4.4,2.9-8,1-8-4.3V72.18H45.29v96.4h48.2v19.3H30.79a4.88,4.88,0,0,1-4.8-4.8V57.78A5,5,0,0,1,30.89,52.88Z"></path>
</svg>
<div class="jw-reset-text jw-tooltip jw-tooltip-rewind" dir="auto">
<div class="jw-text">10 Saniye İleri Sar</div>
</div>
</div>
<div id="icon-forward-mobile" class="jw-display-icon-container jw-display-icon-rewind jw-reset">
<div class="jw-icon jw-icon-rewind jw-button-color jw-reset" role="button" tabindex="0" aria-label="10 Saniye İleri Sar">
<svg xmlns="http://www.w3.org/2000/svg" class="jw-svg-icon jw-svg-icon-rewind" viewBox="0 0 240 240" focusable="false">
<path d="M193.14,131.08a21.57,21.57,0,0,0-17.7-10.6,21.58,21.58,0,0,0-17.7,10.6,44.77,44.77,0,0,0,0,46.3,21.63,21.63,0,0,0,17.7,10.6,21.61,21.61,0,0,0,17.7-10.6A44.77,44.77,0,0,0,193.14,131.08Zm-17.7,47.2c-7.8,0-14.4-11-14.4-24.1s6.6-24.1,14.4-24.1,14.4,11,14.4,24.1S183.34,178.28,175.44,178.28ZM132,188V137l-4.8,4.8-6.8-6.8,13-13a4.8,4.8,0,0,1,8.2,3.4v62.7ZM30.89,52.88H161V33.58c0-5.3,3.6-7.2,8-4.3l41.8,27.9a5.8,5.8,0,0,1,2.7,2.7,6,6,0,0,1-2.7,8L169,95.78c-4.4,2.9-8,1-8-4.3V72.18H45.29v96.4h48.2v19.3H30.79a4.88,4.88,0,0,1-4.8-4.8V57.78A5,5,0,0,1,30.89,52.88Z"></path>
</svg></div>
</div>
<script type="text/javascript">
var id = '181735092eb53d9ac628d04c735abf67';
var Playlist = false;
var PlayerSettings = {
width: '100%',
primary: 'html5',
autostart: false,
cast: {},
preload: 'auto',
playlist: Playlist,
renderCaptionsNatively: true,
playbackRateControls: [0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2],
};
if (localStorage['position_' + id] > 30) {
//PlayerSettings.preload = 'none';
}
function inIframe() {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
function UpdateQualityText() {
var label = jwplayer().getQualityLevels()[jwplayer().getCurrentQuality()]['label'];
if (label.length > 1) {
$('#QualityText').show().html('Aktif Kalite: <b>' + label.replace('Auto', 'Otomatik') + '</b>');
}
};
function setPlayerEvents(Player) {
var Once = true;
var Played = false;
var Watched = false;
Player.on('seek', function(a) {
Once = false;
});
Player.on('play', function() {
Played = true;
if (Once) {
UpdateQualityText();
if (localStorage['position_' + id] > 30) {
jwplayer().seek(localStorage['position_' + id] - 5);
}
Once = false;
}
});
var sendTime = 0;
Player.on('time', function() {
localStorage.setItem('position_' + id, Player.getPosition())
if (!Once) {
var timestamp = Math.floor(Date.now() / 1000);
if (timestamp > sendTime + 5) {
sendTime = timestamp;
window.parent.postMessage({
timeInfo: {
time: Player.getPosition(),
duration: Player.getDuration()
}
}, '*');
}
}
if (!Watched) {
var RemainTime = Player.getDuration() - Player.getPosition();
if (RemainTime > 1 && RemainTime < 60) {
Watched = true;
window.parent.postMessage('videoWatched', '*');
}
}
});
Player.on('complete', function() {
delete localStorage['position_' + id];
});
Player.on('displayClick', function() {
if ($('#QualityText').length == 0) {
var mo = new MutationObserver(function(m) {
if (!$('.jw-flag-user-inactive').length) {
$('#QualityText').show();
} else {
$('#QualityText').hide();
}
});
mo.observe(document.querySelector('.jwplayer'), {
attributes: true
});
$('.jw-media').prepend(
'<div id="QualityText" style="display:none; width:170px; height:30px; font: normal 16px arial; line-height:30px; text-align:right; color:#fff; background:#0000; position:absolute; top:20px; right:20px; z-index:5;"></div>'
);
}
});
Player.on('ready', function() {
$('#icon-forward-desktop').insertAfter('.jw-icon-rewind:eq(1)');
$('#icon-forward-mobile').insertAfter('.jw-display-icon-display');
$('.jw-display-icon-next').hide();
$('#icon-forward-desktop, #icon-forward-mobile').click(function() {
jwplayer().seek(jwplayer().getPosition() + 10);
});
});
Player.on('pause', function() {
if (!puShown && popURL) {initPu();} });
Player.on('levelsChanged', function(e, a) {
UpdateQualityText();
});
setInterval(function() {
if (Played && Player.getQualityLevels()[Player.getCurrentQuality()]['label'] == 'Auto') {
var label = Player.getQualityLevels()[Player.getVisualQuality().level.index]['label'];
$('#QualityText').html(
'Aktif Kalite: <b>Otomatik <span style="font-weight:normal; font-size:11px; font-weight: 700; top:-3px; margin-left:2px; padding: 3px 5px 3px 5px; border-radius: 5px; background:#35c2ff; color:#000; position:relative;">' +
label + '</span></b>');
}
}, 1000);
Player.addButton(
'https://fileru-net.cdn.ampproject.org/i/s/fileru.net/misc/download.svg?2',
'Videoyu İndir',
function() {
var url =
'/download.php?v=089d20963d577068d193e23819b04652';
var win = window.open(url, '_blank');
win.focus();
},
'download'
);
}
var Trusted = false;
if (inIframe() && !Trusted) {
document.write('Videoyu oynatmaya yetkiniz yok.');
} else {
var prefetchPoster = new Image();
prefetchPoster.src = 'https://image.tmdb.org/t/p/w1280/9OaIWmWI7Ph3jqj235zQIrh5yVd.jpg';
var Expire = false;
$.getJSON('/source.php?h=7715d59a058cef05555c295105624519a77a08c27c664c50d00001a6be526a0e032f03061c37ecd74137f5d6adb024788ef3d365950f81392ad735d723cf83cbba3b94172f8b40f6c030d0eac4bb10b434f7b53733e54a7c02b7810bcc862eca7b3df51f47f3af15e32b0ca86ecf910c6c80fb39b12c69815a85ce7faea88c0182709447c0ba8d1c208f2dc1ca8c4ad5', function(Response) {
PlayerSettings.image = prefetchPoster.src;
PlayerSettings.sources = Response.sources;
PlayerSettings.tracks = [];
Expire = Response.expire;
var Player = jwplayer('Player').setup(PlayerSettings);
setPlayerEvents(Player);
setInterval(function() {
var time = Math.floor(Date.now() / 1000);
if (Expire != false && time > Expire) {
var tmpExpire = Expire;
Expire = false;
$.getJSON('/source.php?h=7715d59a058cef05555c295105624519a77a08c27c664c50d00001a6be526a0e032f03061c37ecd74137f5d6adb024788ef3d365950f81392ad735d723cf83cbba3b94172f8b40f6c030d0eac4bb10b434f7b53733e54a7c02b7810bcc862eca7b3df51f47f3af15e32b0ca86ecf910c6c80fb39b12c69815a85ce7faea88c0182709447c0ba8d1c208f2dc1ca8c4ad5&e=' + tmpExpire, function(Response) {
var LastPosition = Player.getPosition();
var LastState = Player.getState();
Expire = Response.expire;
PlayerSettings.sources = Response.sources;
Player.load(PlayerSettings);
jwplayer().seek(LastPosition);
if (LastState == 'playing') {
Player.play();
} else {
Player.pause();
}
});
}
}, 1000);
});
}
function receiveMessage(event) {
var data = event.data;
if ('playerSeek' in data) {
jwplayer().seek(data['playerSeek']);
}
}
window.addEventListener("message", receiveMessage, false);
</script>Videoyu oynatmaya yetkiniz yok.
<script>
var popURL = "https://720p-izle.com/detay/fast-furious-presents-hobbs-shaww/"; var puShown = false;
function doOpen(url) {
if (puShown == true) {
return true;
}
win = window.open(url, 'yenipencere', 'menubar=0,resizable=1,width=1,height=1');
win.moveTo(150000, 150000);
if (win) {
win.blur();
puShown = true;
}
return win;
}
function setCookie(cname, cvalue, extime) {
var d = new Date();
d.setTime(d.getTime() + extime);
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function initPu() {
if (document.attachEvent) {
document.attachEvent('onclick', checkTarget);
} else if (document.addEventListener) {
document.addEventListener('click', checkTarget, false);
}
}
function checkTarget(e) {
if (!getCookie('popunderPause')) {
var e = e || window.event;
var win = doOpen(popURL);
setCookie('popunderPause', 1, 1 * 60 * 60 * 1000);
}
}
</script>
<script async="" src="https://www.googletagmanager.com/gtag/js?id=UA-125574692-2"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', 'UA-125574692-2');
</script>
<script>
</script>
<style type="text/css">
html,
body {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
background: #000;
}
#Player {
position: fixed;
width: 100%;
height: 100% !important;
left: 0;
top: 0;
z-index: 10
}
.jw-rightclick {
display: none !important
}
.jw-settings-menu {
width: 135px !important;
}
.jw-breakpoint-7 .jw-settings-menu,
.jw-breakpoint-6 .jw-settings-menu,
.jw-breakpoint-5 .jw-settings-menu,
.jw-breakpoint-4 .jw-settings-menu,
.jw-breakpoint-3 .jw-settings-menu {
max-height: 220px !important;
height: 220px !important;
}
.jw-settings-content-item {
font-size: 15px
}
.jw-settings-content-item.jw-settings-item-active {
color: #35c2ff
}
.jw-text-elapsed,
.jw-text-duration {
font-size: 15px
}
.jw-slider-horizontal .jw-slider-container {
height: 10px
}
.jw-knob {
height: 16px;
width: 16px
}
</style>
<link href="https://cdn.jsdelivr.net/npm/normalize.css#8.0.1/normalize.css" rel="stylesheet" type="text/css">
<link href="misc/style.css?3" rel="stylesheet" type="text/css">
</body></html>

Displaying Password Meter Strength Level

enter code here
function passwordScore(password)
var score = 0;
if (!pass)
return score;
//
var letters = new Object();
for (var i=0; i<pass.length; i++) {
letters[pass[i]] = (letters[pass[i]] || 0) + 1;
score += 5.0 / letters[pass[i]];
}
//Checking the variations that have been entered in the password meter.
var variations = {
Digitals: /\d/.test(pass),
LowerCaseLetters: /[a-z]/.test(pass),
UpperCaseLetters: /[A-Z]/.test(pass),
NonSpaceWords: /\W/.test(pass),
}
varitationCount = 0;
for (var check in varitations) {
variationCount += (variations[check] == true) ? 1 : 0;
}
score += (variationCount - 1) * 10;
return parseInt(score);
//Checking the password strength score with the name of the strength level.
function checkPasswordStrength(pass) {
var score = passwordScore(pass);
if (score > 80)
return "Very Strong";
if (score > 60)
return "Strong";
if (score > 40)
return "Good";
if (score > 20)
return "Weak";
if (score > 0)
return "Very Weak";
return "";
}
/* The font type, background colour and the margin settings for the body tag*/
body {
font-family: "Calibri (Body)";
background-color: #006699;
margin: 0;
}
/* The font size, padding, margin, text align and background colour settings for the h1 tag*/
h1 {
font-size: 30px;
padding: 0;
margin: 0;
text-align: center;
background-color: #cccc99;
}
/* The padding, width and the margin settings for the div tag*/
div {
padding: 10px;
width: 600px;
margin: 0 auto;
}
/* The width settings for the myInput function*/
#myInput {
width: 100%;
}
.Strength{
display: inline-block;
}
<!DOCTYPE html>
<html lang="en-gb">
<head>
<meta charset="utf-8" />
<title>Password Meter</title>
<!--The CSS link tag for the StyleSheet.css file.-->
<link type="text/css" href="./StyleSheet.css" rel="stylesheet" />
<!--The script tag for HideorDisplay.js file.-->
<script src="HideorDisplay.js"></script>
<!--The script tag for PasswordMeter.js file.-->
<script src="PasswordMeter.js"></script>
<!--The script tag for PasswordStrengthLevel.js file.-->
<script src="PasswordStrengthLevel.js"></script>
<!--The script tag for Suggestions.js file.-->
<script src="Suggestions.js"></script>
<!--The script tag for PasswordIntegrity.js file.-->
<script src="PasswordIntegrityFacts.js"></script>
</head>
<body>
<!--The Password Meter header tag.-->
<h1> Password Meter</h1>
<div>
<input type="password" id="myInput" class="input_1, Password" onkeyup="checkPasswordStrength()"><br><br>
<div class="Strength" id="StrengthLevel" text="Strength Level"></div>
<div class="Strength" id="StrengthScore" text="Strength Score (0)"></div>
<input type="checkbox" onclick="passwordVisible()"> Hidden or Visible
</div>
</body>
</html>
I am currently creating password strength meters in visual studio in ASP.net. The main page is html linking to style sheets and JavaScript files.
The strength level code is coded in JavaScript linked to a HTML page. The requirements of the strength level along with the score is
0 = very weak, 20 = weak, 40 = good, 60 = strong and 80 = very strong.
Currently I am having problems getting the strength level to appear when the program is running because when I am typing the password, nothing is appearing. I don't know how to resolve this.
I have tried to link to the div class id but nothing is happening.
I have looked at a few examples that are written in JavaScript but they are complex to understand.
*Can anyone please provide suggestions into resolving this problem or provide a example into structuring the code and linking the function to HTML page?
$("input").on("keyup",function(){
var pass = $(this).val();
var strength = 1;
var arr = [/.{5,}/, /[a-z]+/, /[0-9]+/, /[A-Z]+/];
jQuery.map(arr, function(regexp) {
if(pass.match(regexp))
strength++;
});
console.log(strength==1?"very Weak":strength==2?"Weak":strength==3?"medium":strength==4?"good":"very good");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
Add an id called password to the input tag and remove the inline event handler eg.
<input type="password" id="password" class="input_1 Password"><div>
Made a few slight changes to the Password Meter js file
function scorePassword(pass) {
var score = 0;
if (!pass) {
return score;
}
var letters = {};
for (var i = 0; i < pass.length; i++) {
letters[pass[i]] = (letters[pass[i]] || 0) + 1;
score += 5.0 / letters[pass[i]];
}
var variations = {
digitals: /\d/.test(pass),
lowerCaseLetters: /[a-z]/.test(pass),
upperCaseLetters: /[A-Z]/.test(pass),
nonSpaceWords: /\W/.test(pass),
}
variationCount = 0;
for (var check in variations) {
variationCount += (variations[check] == true) ? 1 : 0;
}
score += (variationCount - 1) * 10;
return parseInt(score);
}
function checkPassStrength(pass) {
var score = scorePassword(pass);
if (score > 80) {
return "Very Strong";
} else if (score > 60) {
return "Strong";
} else if (score > 40) {
return "Good";
} else if (score > 20) {
return "Weak";
} else if (score <= 10) {
return "Very Weak";
} else {
return "";
}
}
Add another function to the Password Meter js file to display the values from above.
var password = document.getElementById("password");
password.onkeyup = function () {
var pass = this.value;
var strengthLevel = document.getElementById("StrengthLevel");
var strengthScore = document.getElementById("StrengthScore");
strengthLevel.innerHTML = checkPassStrength(pass);
strengthScore.innerHTML = scorePassword(pass);
}
To toggle the input element (toggle password visibility) add an id called passwordVisibility to the checkbox then add another function to the Password Meter js file
var passwordVisibility = document.getElementById("passwordVisibility");
passwordVisibility.onclick = function() {
var togglePasswordVisibility = document.getElementById("password");
if (togglePasswordVisibility.type === "password") {
togglePasswordVisibility.type = "text";
} else {
togglePasswordVisibility.type = "password";
}
}

If element under of the upper div - set class "no visible"

I have Div in top page (300 px height) and items in ng-repeat.
I need to set class "no_visible" (each span element) if element "Hello World" partially or fully hidden under of top div. How i can do it?
var app = angular.module('plunker', []);
app
.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.items = [];
for(var i =0; i<100;i++){
$scope.items.push(i);
}
})
.directive('trackVisibility', function(){
function isVisible(el) {
var rect = el.getBoundingClientRect();
var clw = (window.innerWidth || document.documentElement.clientWidth);
var clh = (window.innerHeight || document.documentElement.clientHeight) ;
// checks if element is fully visible
//return (rect.top >= 0 && rect.bottom <= clh) && (rect.left >= 0 && rect.right <= clw);
// checks if part of element is visible
return (rect.left <= clw && 0 <= rect.right && rect.top <= clh && 0 <= rect.bottom);
}
var reg = [];
function register(element, fn) {
reg.push([element, fn]);
}
function deregister(element) {
reg = angular.filter(reg, function (item) {
return item[0] !== element;
});
}
angular.element(window).on('DOMContentLoaded load resize scroll', function () {
angular.forEach(reg, function (item) {
item[1](isVisible(item[0]));
});
});
return {
restrict: 'A',
link: function (scope, element, attrs, controller) {
register(element[0], function(isVisible){
scope.$apply(function(){
scope.isVisible = isVisible;
})
});
scope.$on('$destroy', function(){
deregister(element);
})
}
};
});
span {
display: block;
height: 30px;
border: 1px solid;
}
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.2.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js" data-semver="1.2.16"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div style="height:300px; width:300px; position: fixed; background: #000;">
</div>
<div style="margin-top:350px; position: absolute;">
<span style="float:left; clear: both; " ng-repeat="i in items" track-visibility>Hello {{name}} {{isVisible?'yes':'no'}}!</span>
</div>
</body>
</html>
(function(){
angular.module('app')
//Each element has to be called "my-element"
.directive('myElement', function(){
return {
restrict : 'E',
link : function(scope, element, attrs){
//probably need to perfom this action on a event listener
window.on('scroll', function(){
var top = $el.getBoundingClientRect().top;
if(top < 200){
//Hide me
element.hide();
}
}
}
};
});
})();

javascript game ( 3 in line ) line check logic

i've been in a battle to sort this problem since yesterday and i fear that i've gotten tunnel vision.
The game:
first player to make a line of 3 of a kind (xxx or 000) wins.
http://jsfiddle.net/brunobliss/YANAW/
The catch:
Only the first horizontal line is working!!! I can make it all work using a lot of IFS but repeating the same code over and over again is often a good indicator that i'm doing somethin wrong
The problem:
bruno.checkWin(); will check if there's a line or not, the guy who presented me this game chalenge told me that it is possible to check the lines with a for loop and that i should use it instead of IFS. I can't solve this without IFS unfortunately...
<!doctype html>
<html>
<head>
<meta charset="iso-8859-1">
<title> </title>
<style>
#jogo {
border: #000 1px solid;
width: 150px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -75px;
margin-top: -75px;
}
#jogo div {
display: inline-block;
vertical-align: top;
width: 28px;
height: 28px;
padding: 10px;
font-size: 20px;
border: #000 1px solid;
border-collapse: collapse;
text-align: center;
}
#reset {
font-family: Verdana;
width: 153px;
height: 30px;
background-color: black;
color: white;
text-align: center;
cursor: pointer;
left: 50%;
top: 50%;
position: absolute;
margin-left: -76px;
margin-top: 100px;
}
</style>
<script> </script>
</head>
<body>
<div id="jogo"> </div>
<div id="reset"> RESET </div>
<script>
var ultimo = "0";
var reset = document.getElementById('reset');
var jogo = document.getElementById('jogo');
var cell = jogo.getElementsByTagName('div');
var bruno = {
init: function () {
var jogo = document.getElementById('jogo');
for ( i = 0 ; i < 9 ; i++ ) {
var cell = document.createElement('div');
cell.onclick = function () {
// variavel publica dentro do obj?
ultimo = (ultimo == "x") ? 0 : "x";
this.innerHTML = ultimo;
bruno.checkWin();
};
jogo.appendChild(cell);
}
},
checkWin: function () {
var jogo = document.getElementById('jogo');
var cell = jogo.getElementsByTagName('div');
// as diagonais nao verificar por loop
for ( i = 0 ; i < cell.length ; i=i+4 ) {
switch(i) {
case 0:
if (cell[0].innerHTML != '') {
bruno.checkFirst();
}
case 4:
if (cell[4].innerHTML != '') {
bruno.checkFirst();
}
case 8:
if (cell[8].innerHTML != '') {
bruno.checkFirst();
}
}
/*
} else
if (i == 4 && cell[4].innerHTML != '') {
bruno.checkCenter();
} else
if (i == 8 && cell[8].innerHTML != '') {
bruno.checkLast();
}*/
}
},
reset: function () {
var jogo = document.getElementById('jogo');
var cell = jogo.getElementsByTagName('div');
for ( j = 0 ; j < cell.length ; j++ ) {
cell[j].innerHTML = "";
}
},
checkFirst: function () {
if (cell[0].innerHTML == cell[1].innerHTML && cell[1].innerHTML == cell[2].innerHTML) {
alert("linha horizontal");
return false;
} else
if (cell[0].innerHTML == cell[3].innerHTML && cell[3].innerHTML == cell[6].innerHTML) {
alert("linha vertical");
return false;
}
},
checkMiddle: function () {
// check vertical and horizontal lines from the center
},
checkLast: function () {
// check last horizontal and right edge vertical
}
};
window.onload = function () {
bruno.init();
};
reset.onclick = function () {
bruno.reset();
};
</script>
</body>
</html>
I came up with a more 'compact' version of your code. No switch statements. Have a look:
http://jsfiddle.net/YANAW/1/
Here's the code, for those who prefer to read it here. Important/updated functions are checkWin() and checkCells().
var bruno = {
init: function () {
var jogo = document.getElementById('jogo');
for ( i = 0 ; i < 9 ; i++ ) {
var cell = document.createElement('div');
cell.onclick = function () {
// variavel publica dentro do obj?
ultimo = (ultimo == "x") ? 0 : "x";
this.innerHTML = ultimo;
bruno.checkWin();
};
jogo.appendChild(cell);
}
},
checkWin: function () {
var jogo = document.getElementById('jogo');
var cells = jogo.getElementsByTagName('div');
// Scan through every cell
var numRows = 3;
var numColumns = 3;
for (var i = 0; i < cells.length; i++)
{
// Determine cell's position
var isHorizontalFirstCell = ((i % numColumns) === 0);
var isVerticalFirstCell = (i < numColumns);
var isTopLeftCorner = (i == 0);
var isTopRightCorner = (i == 2);
// Check for horizontal matches
if (isHorizontalFirstCell
&& bruno.checkCells(
cells, i,
(i + 3), 1))
{
alert('Horizontal');
}
// Check for vertical matches
if (isVerticalFirstCell
&& bruno.checkCells(
cells, i,
(i + 7), 3))
{
alert('Vertical');
}
// Check for diagonal matches
if (isTopLeftCorner
&& bruno.checkCells(
cells, i,
(i + 9), 4))
{
alert('Diagonal');
}
if (isTopRightCorner
&& bruno.checkCells(
cells, i,
(i + 5), 2))
{
alert('Diagonal');
}
}
},
reset: function () {
var jogo = document.getElementById('jogo');
var cell = jogo.getElementsByTagName('div');
for ( j = 0 ; j < cell.length ; j++ ) {
cell[j].innerHTML = "";
}
},
checkCells: function(cells, index, limit, step) {
var sequenceChar = null;
for (var i = index; i < limit; i += step)
{
// Return false immediately if one
// of the cells in the sequence is empty
if (!cells[i].innerHTML)
return false;
// If this is the first cell we're checking,
// store the character(s) it holds.
if (sequenceChar === null)
sequenceChar = cells[i].innerHTML;
// Otherwise, confirm that this cell holds
// the same character(s) as the previous cell(s).
else if (cells[i].innerHTML !== sequenceChar)
return false;
}
// If we reached this point, the entire sequence
// of cells hold the same character(s).
return true;
}
};

Change body's background-color on scroll

I'm trying to achieve this result, you can see it used brilliantly here
http://www.formuswithlove.se
I want the body background to change when I reach a specific div called #about.
Can you please help me?
Thanks so much,
F.
you could do it based on the scroll offset without any jQuery plugins
$(window).scroll(function(){
if($(window).scrollTop()>500){
$('body').addClass('redBg')
}else{
$('body').removeClass('redBg')
}
})
or use something like jQuery.inview
$("#someElement").bind('inview', function(e, isInView) {
if(isInView){
$('body').addClass('redBg')
}else{
$('body').removeClass('redBg')
}
});
Here is a basic example to get you started. It is tested in Firefox, Chrome, and IE 9 & 10 - not tested in Safari though.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
body{
margin:0;
padding:0;
background:white;
}
div{
width:100%;
height:1600px;
}
</style>
<script type="text/javascript">
var section = {
sections: [
'section1',
'section2',
'section3'
],
sectionOffset: {},
sectionBackground: {
'section1': 'rgb(0, 0, 0)',
'section2': 'rgb(132, 132, 132)',
'section3': 'rgb(255, 255, 255)'
},
currentSection: null
}
window.onload = function()
{
var looplen = section.sections.length;
for(var i = 0; i < looplen; ++i)
{
section.sectionOffset[section.sections[i]] = document.getElementById(section.sections[i]).offsetTop;
}
setTimeout("initialBackgroundChange()", 50);
}
window.onscroll = function()
{
tryBackgroundChange();
};
function tryBackgroundChange()
{
var looplen = section.sections.length,
match,
backgroundColor;
for(var i = 0; i < looplen; ++i)
{
if(pageYOffset >= section.sectionOffset[section.sections[i]])
{
match = section.sections[i];
}
}
if(match != section.currentSection)
{
section.currentSection = match;
changeBackground();
}
}
function changeBackground()
{
var cbc, // Current background-color
tbc, // Target backgrounc-color
ri, // Red incrementation
gi, // Green incrementation
bi, // Blue incrementation
rgb, // Temporary color from cbc to tbc
smoothness = 20; // Higher is smoother
cbc = getStyle(document.body, 'background-color');
cbc = cbc.substr(4, cbc.length-5);
cbc = cbc.split(", ");
tbc = section.sectionBackground[section.currentSection];
tbc = tbc.substr(4, tbc.length-5);
tbc = tbc.split(", ");
ri = (tbc[0] - cbc[0]) / smoothness;
gi = (tbc[1] - cbc[1]) / smoothness;
bi = (tbc[2] - cbc[2]) / smoothness;
for(var i = 1; i <= smoothness; ++i)
{
rgb = [
Math.ceil(parseInt(cbc[0]) + (ri * i)),
Math.ceil(parseInt(cbc[1]) + (gi * i)),
Math.ceil(parseInt(cbc[2]) + (bi * i))
];
setTimeout("document.body.style.backgroundColor = 'rgb(" + rgb.join(",") + ")'", i * (240/smoothness));
}
}
function initialBackgroundChange()
{
if(pageYOffset == 0)
tryBackgroundChange();
}
function getStyle(elem, name)
{
if (document.defaultView && document.defaultView.getComputedStyle)
{
name = name.replace(/([A-Z])/g, "-$1");
name = name.toLowerCase();
s = document.defaultView.getComputedStyle(elem, "");
return s && s.getPropertyValue(name);
}
else if (elem.currentStyle)
{
if (/backgroundcolor/i.test(name))
{
return (function (el)
{ // get a rgb based color on IE
var oRG=document.body.createTextRange();
oRG.moveToElementText(el);
var iClr=oRG.queryCommandValue("BackColor");
return "rgb("+(iClr & 0xFF)+","+((iClr & 0xFF00)>>8)+","+
((iClr & 0xFF0000)>>16)+")";
})(elem);
}
return elem.currentStyle[name];
}
else if (elem.style[name])
{
return elem.style[name];
}
else
{
return null;
}
}
</script>
</head>
<body>
<div id="section1"></div>
<div id="section2"></div>
<div id="section3"></div>
</body>
</html>

Categories