SVG Clipping Issue (HTML, JS, JQUERY, CSS) - javascript
I am trying to incorporate a preloader within my site and I would like the splash screen's loading bar to be in the shape of a custom logo. I have successfully created a clipping svg on text and images before, so I don't believe that this is where the problem is (see my jsfiddle).
I just need the loading bar's containing svg to clip the loading bar div in the shape of the inline svg.
I have included my code.
Thanks.
(function($) {
var items = new Array(),
errors = new Array(),
onComplete = function() {},
current = 0;
var jpreOptions = {
splashVPos: '35%',
loaderVPos: '75%',
splashID: '#jpreContent',
showSplash: true,
showPercentage: false,
autoClose: true,
onetimeLoad: false,
debugMode: false,
splashFunction: function() {}
}
//cookie
var getCookie = function() {
if( jpreOptions.onetimeLoad ) {
var cookies = document.cookie.split('; ');
for (var i = 0, parts; (parts = cookies[i] && cookies[i].split('=')); i++) {
if ((parts.shift()) === "jpreLoader") {
return (parts.join('='));
}
}
return false;
} else {
return false;
}
}
var setCookie = function(expires) {
if( jpreOptions.onetimeLoad ) {
var exdate = new Date();
exdate.setDate( exdate.getDate() + expires );
var c_value = ((expires==null) ? "" : "expires=" + exdate.toUTCString());
document.cookie="jpreLoader=loaded; " + c_value;
}
}
//create jpreLoader UI
var createContainer = function() {
jOverlay = $('<div></div>')
.attr('id', 'jpreOverlay')
.css({
position: "fixed",
top: 0,
left: 0,
width: '100%',
height: '100%',
zIndex: 9999999
})
.appendTo('body');
jLoader = $('<svg></svg>')
.attr('id', 'jpreLoader')
.appendTo(jOverlay);
var posWidth = $(window).width() - $(jLoader).width();
$(jLoader).css({
position: 'absolute',
top: jpreOptions.loaderVPos,
left: Math.round((50 / $(window).width()) * posWidth) + '%'
});
jBar = $('<div></div>')
.attr('id', 'jpreBar')
.css({
width: '0%',
height: '100%'
})
.appendTo(jLoader);
}
//get all images from css and <img> tag
var getImages = function(element) {
$(element).find('*:not(script)').each(function() {
var url = "";
if ($(this).css('background-image').indexOf('none') == -1 && $(this).css('background-image').indexOf('-gradient') == -1) {
url = $(this).css('background-image');
if(url.indexOf('url') != -1) {
var temp = url.match(/url\((.*?)\)/);
url = temp[1].replace(/\"/g, '');
}
} else if ($(this).get(0).nodeName.toLowerCase() == 'img' && typeof($(this).attr('src')) != 'undefined') {
url = $(this).attr('src');
}
if (url.length > 0) {
items.push(url);
}
});
}
//create preloaded image
var preloading = function() {
for (var i = 0; i < items.length; i++) {
if(loadImg(items[i]));
}
}
var loadImg = function(url) {
var imgLoad = new Image();
$(imgLoad)
.load(function() {
completeLoading();
})
.error(function() {
errors.push($(this).attr('src'));
completeLoading();
})
.attr('src', url);
}
//update progress bar once image loaded
var completeLoading = function() {
current++;
var per = Math.round((current / items.length) * 100);
$(jBar).stop().animate({
width: per + '%'
}, 500, 'linear');
if(jpreOptions.showPercentage) {
$(jPer).text(per+"%");
}
//if all images loaded
if(current >= items.length) {
current = items.length;
setCookie(); //create cookie
if(jpreOptions.showPercentage) {
$(jPer).text("100%");
}
//fire debug mode
if (jpreOptions.debugMode) {
var error = debug();
}
//max progress bar
$(jBar).stop().animate({
width: '100%'
}, 500, 'linear', function() {
//autoclose on
if( jpreOptions.autoClose )
loadComplete();
});
}
}
//triggered when all images are loaded
var loadComplete = function() {
$(jOverlay).fadeOut(800, function() {
$(jOverlay).remove();
onComplete(); //callback function
});
}
//debug mode
var debug = function() {
if(errors.length > 0) {
var str = 'ERROR - IMAGE FILES MISSING!!!\n\r'
str += errors.length + ' image files cound not be found. \n\r';
str += 'Please check your image paths and filenames:\n\r';
for (var i = 0; i < errors.length; i++) {
str += '- ' + errors[i] + '\n\r';
}
return true;
} else {
return false;
}
}
$.fn.jpreLoader = function(options, callback) {
if(options) {
$.extend(jpreOptions, options );
}
if(typeof callback == 'function') {
onComplete = callback;
}
//show preloader once JS loaded
$('body').css({
'display': 'block'
});
return this.each(function() {
if( !(getCookie()) ) {
createContainer();
getImages(this);
preloading();
}
else { //onetime load / cookie is set
$(jpreOptions.splashID).remove();
onComplete();
}
});
};
})(jQuery);
body{
display:none;
}
#jpreOverlay {
background-color: rgba(000, 000, 000, 0.87);
}
#jpreLoader{
width:300px;
height:300px;
}
#jpreBar {
background-size:30px 30px;
-moz-background-size:30px 30px;
-webkit-background-size:30px 30px;
-o-background-size:30px 30px;
filter: progid:DXImageTransform.Microsoft.gradient(
startColorstr='#33ffffff',
endColorstr='#33000000',
GradientType=0 );
background-color:#E07300;
clip-path: url(#clipping);
-webkit-clip-path: url(#clipping);
-moz-clip-path: url(#clipping);
-o-clip-path: url(#clipping);
position: absolute;
}
#-webkit-keyframes progress {
from {
background-position: 0 0;
}
to {
background-position: -60px -60px;
}
}
#-moz-keyframes progress {
from {
background-position: 0 0;
}
to {
background-position: -60px -60px;
}
}
#-ms-keyframes progress {
from {
background-position: 0 0;
}
to {
background-position: -60px -60px;
}
}
#-o-keyframes progress {
from {
background-position: 0 0;
}
to {
background-position: -60px -60px;
}
}
#keyframes progress {
from {
background-position: 0 0;
}
to {
background-position: -60px -60px;
}
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jPreLoader v2 - A jQuery preloader for Website</title>
<link rel="stylesheet" href="css/jpreloader.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="js/jpreloader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<link rel="shortcut icon" href="http://www.inwebson.com/wp-content/themes/inwebson2/favicon.ico" />
<link rel="canonical" href="http://www.inwebson.com/demo/jpreloader-v2/" />
</head>
<body>
<section id="wrapper">
<div class="wrapper-inner">
<hgroup>
<h2>jPreLoader v2</h2>
<h3>A loading screen to preload images using jQuery</h3>
</hgroup>
<div class="container">
<ul id="set1" class="holder current">
<li><img src="http://sphotos-b.ak.fbcdn.net/hphotos-ak-snc6/181548_153793501342544_153515891370305_259700_7241508_n.jpg" /></li>
<li><img src="http://sphotos-b.ak.fbcdn.net/hphotos-ak-snc6/196528_158118380910056_153515891370305_283882_234528_n.jpg" /></li>
<li><img src="http://sphotos-b.ak.fbcdn.net/hphotos-ak-snc6/196556_159931940728700_153515891370305_293999_6261181_n.jpg" /></li>
<li><img src="http://sphotos-b.ak.fbcdn.net/hphotos-ak-ash4/205687_165495210172373_153515891370305_326385_1869822_n.jpg" /></li>
<li><img src="http://sphotos-b.ak.fbcdn.net/hphotos-ak-snc6/205600_167760236612537_153515891370305_338177_2160812_n.jpg" /></li>
<li><img src="http://sphotos-b.ak.fbcdn.net/hphotos-ak-snc6/248150_174306909291203_153515891370305_374445_3774819_n.jpg" /></li>
<li><img src="http://sphotos-b.ak.fbcdn.net/hphotos-ak-snc6/228343_171546129567281_153515891370305_358267_5126730_n.jpg" /></li>
<li><img src="http://sphotos-b.ak.fbcdn.net/hphotos-ak-ash4/249232_174478049274089_153515891370305_375652_2662480_n.jpg" /></li>
<li><img src="http://sphotos-b.ak.fbcdn.net/hphotos-ak-snc6/268903_186646411390586_153515891370305_435046_34596_n.jpg" /></li>
<div class=clearfix></div>
</ul>
<ul id="set2" class="holder">
<li><div id="li1"></div></li>
<li><div id="li2"></div></li>
<li><div id="li3"></div></li>
<li><div id="li4"></div></li>
<li><div id="li5"></div></li>
<li><div id="li6"></div></li>
<li><div id="li7"></div></li>
<li><div id="li8"></div></li>
<li><div id="li9"></div></li>
</ul>
<div class="clearfix"></div>
</div>
<div class="description txtright">
Images by Mike Shaw, Cheshire UK based photographer.
</div>
</div>
</section>
<!-- This section is for Splash Screen -->
<section id="jSplash">
<section class="selected">
<svg width="82" height="82" id="jpreLoader" clipPathUnits="objectBoundingBox">
<defs>
<clipPath id="clipping">
<path stroke-opacity="0" fill-opacity="1" stroke-width="0" stroke="none" fill="#282525" d="M244,121.9L250.5,123.2C239.2,127.9 228.9,132.6 221.4,138.2L212.2,138.2L212.2,147.3C212.2,157.7 224.6,172.8 233.2,182.2L238.1,182.2C253.2,200.4 299.6,221.8 320.6,232.1C309.8,235.3 290.9,234.3 281.2,230.2L258.6,220.8C251,219.6 241.9,218.9 235.4,221.5C217.6,213.3 198.7,207 205.2,202.3C180.4,191.6 168.6,184.1 162.6,176.5L136.7,191.6C133.5,190 127,190.7 123.8,192.6L84.4,214.9C62.9,216.1 35.9,243.4 9.5,243.4C8.4,243.4 7.9,243.1 7.9,242.8C7.9,241.2 16.5,238.1 18.7,236.5C19.2,236.2 19.2,235.9 19.7,235.6L43.5,222.4L42.4,218.6L23.5,228.7C25.1,221.8 23.5,213.3 28.9,204.8L46.7,195.1C48.9,190.7 52.6,186.9 57.5,182.8L65,185L94.2,169C100.6,165.2 111.9,159.6 111.4,152.7C121.6,147.3 130.3,142.3 137.3,136.7C141.6,136.3 145.9,135.7 148.6,133.8C148.6,133.2 147.5,132.3 147.5,131.6C130.3,96.5 128.7,61.6 150.8,26.4C155.1,24.6 162.1,22 165.3,24.6L156.1,41.5C163.2,38.4 167.5,30.5 172.3,24.6C203.1,27.1 203.1,39.3 219.8,39.9L225.7,46.5C216.5,57.5 210.6,74.2 210.1,82.3L206.8,87L211.1,88.6C245.6,68.2 286.6,41.2 319.5,23.6L328.1,23.6L328.1,28C333.5,26.4 338.9,19.2 352.9,20.5L348.1,25.5C372.9,28.6 389.6,36.5 389.6,41.8C389.6,43.4 389.1,45 386.4,46.2L244,121.9M46.7,216.1L48.3,219.3C53.7,217.7 55.9,214.5 55.9,211.7L46.7,216.1M65,181.3L61.3,180.3C66.1,176.9 72,173.4 78,169.9L81.7,172.1L65,181.3M85,170.3L81.2,168.1C84.4,166.5 87.1,164.9 90.4,163.3L90.4,167.1L85,170.3M237.6,138.2L230,138.2L242.9,131.3L247.3,132.3L237.6,138.2M253.2,228.7L240.3,223.3C246.2,221.8 253.7,223.6 262.4,227.7L253.2,228.7z"></path>
</clipPath>
</defs>
</svg>
<h2>jPreLoader v2</h2>
<strong>A loading screen to preload images using jQuery</strong>
</section>
</section>
<!-- End of Splash Screen -->
<script>
$(document).ready( function() {
var timer; //timer for splash screen
//calling jPreLoader
$('body').jpreLoader({
splashID: "#jSplash",
loaderVPos: '30%',
autoClose: false,
splashFunction: function() {
//passing Splash Screen script to jPreLoader
$('#jSplash').children('section').not('.selected').hide();
$('#jSplash').hide().fadeIn(800);
timer = setInterval(function() {
splashRotator();
}, 4000);
},
});
//create splash screen animation
function splashRotator(){
var cur = $('#jSplash').children('.selected');
var next = $(cur).next();
if($(next).length != 0) {
$(next).addClass('selected');
} else {
$('#jSplash').children('section:first-child').addClass('selected');
next = $('#jSplash').children('section:first-child');
}
$(cur).removeClass('selected').fadeOut(800, function() {
$(next).fadeIn(800);
});
}
});
</script>
</body>
</html>
Related
Is there a way to generate images in random positions (javascript)?
I am currently experimenting with a d-i-y collage game, where users can click an image and drag it into a desired position. The code works fine, except at load time all of the images are scrunched up in the top left corner. The are on top of one another and hide those under them. I can't figure out why the random position generation isn't working. The images are in div, as a beginner I don't know if there's another way to do it at the moment. Is Math.random() possible? <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script> let currentlyDragging; let drawing = false;; let offset_x; let offset_y; let puzzle; $(window).load(function () { $(".draggable").click(startDragging); $(".draggable").mousemove(whileDragging); $("#puzzle").mousemove(whileDragging); puzzle = document.getElementById("puzzle"); }); function startDragging(e) { if (!drawing) { drawing = true; currentlyDragging = $(this); if (offset_x == null && offset_y == null) { var current_origin_y; var current_origin_x; var current_origin_y_string = currentlyDragging.context.style['margin-top']; if (current_origin_y_string === "") { current_origin_y = 0; } else { current_origin_y = parseInt(current_origin_y_string.split("px")[0]); } var current_origin_x_string = currentlyDragging.context.style['margin-left']; if (current_origin_x_string === "") { current_origin_x = 0; } else { current_origin_x = parseInt(current_origin_x_string.split("px")[0]); } offset_x = current_origin_x - e.pageX; offset_y = current_origin_y - e.pageY; } } else { drawing = false; currentlyDragging = null; offset_x = null; offset_y = null; } } function whileDragging(e) { if (currentlyDragging == null) { return false; } currentlyDragging.css({ "margin-top": Math.min(Math.max(e.pageY + offset_y, 0), puzzle.clientHeight - currentlyDragging.context.height) + "px", "margin-left": Math.min(Math.max(e.pageX + offset_x, 0), puzzle.clientWidth - currentlyDragging.context.width) + "px" }); } </script> <style> .draggable { position: absolute; cursor: pointer; user-select: none; } </style> <div id="puzzle" scroll="no" style="height: 100%; overflow: hidden; border: 5px solid yellow;"> <img class=draggable src="https://avatars3.githubusercontent.com/u/9167554?s=460&v=4" width=50 height=50 /> <img class=draggable src="https://avatars3.githubusercontent.com/u/9167554?s=460&v=4" width=50 height=50 /> <img class=draggable src="https://avatars3.githubusercontent.com/u/9167554?s=460&v=4" width=50 height=50 /> <img class=draggable src="https://avatars3.githubusercontent.com/u/9167554?s=460&v=4" width=50 height=50 /> <img class=draggable src="https://avatars3.githubusercontent.com/u/9167554?s=460&v=4" width=50 height=50 /> </div> </body>
JavaScript application: trying to make the "wheel" event listener discontinuous fails
I am working on a small "Picture browser" application in Bootstrap 4 and JavaScript. As can be seen below, there is a "Prev" and a "Next" button that help navigate through the pictures. I have bean trying to find a reliable method to make mouse well scrolling function the same as these buttons. Scrolling down would be the equivalent of clicking the "Next" button. Scrolling up would be the equivalent of clicking the "Prev" button. var picArr = $('#pictures_list li'); // The index of the last element of the array is "maxIndex" var maxIndex = picArr.length - 1; // Initialize counter var counter = 0; var updateCounter = function(btn) { var direction = $(btn).data("direction") if (direction === "left") { if (counter > 0) { counter--; } else { counter = maxIndex; } } else { if (counter < maxIndex) { counter++; } else { counter = 0; } } } var showCount = function(container_id) { var pageCount = counter + 1; document.getElementById(container_id).innerHTML = "Picture " + pageCount + " of " + picArr.length; } var showSlide = function() { var mTop = (200 * counter) * (-1) + 'px'; $('#pictures_list').animate({ 'marginTop': mTop }, 400); } showCount('show_count'); $('#controls button').on('click', function() { updateCounter(this); showSlide(); showCount('show_count'); }); document.getElementById("picture_frame").addEventListener("wheel", function() { updateCounter(this); showSlide(); showCount('show_count') }); #picture_frame { width: 200px; height: 200px; margin: 5px auto; border: 1px solid #ccc; border-radius: 2px; overflow: hidden; } .controls>div { display: inline-block; } #picture_frame { height: 200px; overflow: hidden; } #pictures_list { flex-flow: row wrap; align-items: stretch; width: 200px; } #pictures_list li { display: flex; height: 200px; flex: 1 100%; } <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <div id="picture_frame"> <ul id="pictures_list" class="list-unstyled d-flex"> <li><img src="https://picsum.photos/200/200 " alt="First picture"></li> <li><img src="https://picsum.photos/200/200?gravity=east " alt="Second picture"></li> <li><img src="https://picsum.photos/200/200?gravity=west " alt="Third picture"></li> <li><img src="https://picsum.photos/200/200?gravity=north " alt="Fourth picture"></li> </ul> </div> <div class="text-center mb-2"> <span class="badge badge-primary" id="show_count"></span> </div> <div class="controls text-center"> <div class="btn-group" id="controls"> <button type="button" class="btn btn-primary btn-sm" data-direction="left">Prev</button> <button type="button" class="btn btn-primary btn-sm" data-direction="right">Next</button> </div> </div> </div> Firing the showSlide() function on mouse wheel does work, but the transition is too... continuous. I wish it would be identical to the transition triggered by the buttons. What am I missing?
Here are several solutions: -- To prevent the scroll from scrolling multiple images, you can use this function: // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. function debounce(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }; See https://davidwalsh.name/javascript-debounce-function -- You should change the parameter of your function updateCounter so that it takes the direction of scrolling images. (example: boolean: true = next, false = previous) --To recover the direction of the scroll, refer to this answer : https://stackoverflow.com/a/45719399/4864628 var picArr = $('#pictures_list li'); // The index of the last element of the array is "maxIndex" var maxIndex = picArr.length - 1; // Initialize counter var counter = 0; var updateCounter = function(direction) { if (direction) { if (counter > 0) { counter--; } else { counter = maxIndex; } } else { if (counter < maxIndex) { counter++; } else { counter = 0; } } } var showCount = function(container_id) { var pageCount = counter + 1; document.getElementById(container_id).innerHTML = "Picture " + pageCount + " of " + picArr.length; } var showSlide = function() { var mTop = (200 * counter) * (-1) + 'px'; $('#pictures_list').animate({ 'marginTop': mTop }, 400); } // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. function debounce(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }; showCount('show_count'); $('#controls button').on('click', function() { updateCounter($(this).attr('data-direction') == 'left'); showSlide(); showCount('show_count'); }); var pictureFrame = document.getElementById("picture_frame"); var onScroll = debounce(function(direction) { updateCounter(direction); showSlide(); showCount('show_count') }, 100, true); pictureFrame.addEventListener("wheel", function(e) { e.preventDefault(); var delta; if (event.wheelDelta){ delta = event.wheelDelta; }else{ delta = -1 * event.deltaY; } onScroll(delta >= 0); }); #picture_frame { width: 200px; height: 200px; margin: 5px auto; border: 1px solid #ccc; border-radius: 2px; overflow: hidden; } .controls>div { display: inline-block; } #picture_frame { height: 200px; overflow: hidden; } #pictures_list { flex-flow: row wrap; align-items: stretch; width: 200px; } #pictures_list li { display: flex; height: 200px; flex: 1 100%; } <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <div id="picture_frame"> <ul id="pictures_list" class="list-unstyled d-flex"> <li><img src="https://picsum.photos/200/200 " alt="First picture"></li> <li><img src="https://picsum.photos/200/200?gravity=east " alt="Second picture"></li> <li><img src="https://picsum.photos/200/200?gravity=west " alt="Third picture"></li> <li><img src="https://picsum.photos/200/200?gravity=north " alt="Fourth picture"></li> </ul> </div> <div class="text-center mb-2"> <span class="badge badge-primary" id="show_count"></span> </div> <div class="controls text-center"> <div class="btn-group" id="controls"> <button type="button" class="btn btn-primary btn-sm" data-direction="left">Prev</button> <button type="button" class="btn btn-primary btn-sm" data-direction="right">Next</button> </div> </div> </div>
Laravel 5.4 - Code for javascript screensaver in blade not running but have no error in console?
I have here a blade page on laravel 5.4 that allows users to input survey responses. The system should show a screensaver after being idle for a certain time ie. idle is 5mins. but the screensaver should disappear when somebody interact with the page. but the codes did not function. I've check the console but it has no error in google chrome. (newbie in javascript) #php use App\Bus; use App\Bgcroute; use App\Surveyquestion; use App\User; use Controller\UserController; #endphp <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>BGC Bus Survey Page</title> <link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Cookie"> <link rel="stylesheet" href="assets/css/user.css"> <link rel="stylesheet" href="assets/css/Pretty-Footer.css"> <link rel="stylesheet" href="assets/css/Pretty-Header.css"> <link rel="stylesheet" href="assets/css/Hero-Technology.css"> <link rel="stylesheet" href="js-screensaver/screensaver.css"> <script src="js-screensaver/screensaver.js"></script> <script src="sweetalert2.all.js"></script> <script src="sweetalert2.min.js"></script> <link rel="stylesheet" href="sweetalert2.min.js"> <style type="text/css"> .navbar { margin-bottom: 0; border-radius: 0; background-color: #00FFFF; color: #FFF; padding: 1 0; font-size: 1.2em; border: 0; } .navbar-brand { float: left; min-height: 55px; padding: 0 15px; } .img-logo{ width: 75px; height: 60px; } .navbar-inverse .navbar-nav .active a, .navbar-inverse .navbar-nav .active a:focus, .navbar-inverse .navbar-nav .active a:hover { color: #fff; background-color: #53DFF0; } .navbar-inverse .nav-bar-nav li a { color: #D5D5D5; } .avatar{ border-radius: 100%; max-width: 100px; clip: rect(10px,60px,50px,10px); } .startScreenSaver({ timeout: 5000, width: 30, height: 30, exitTimeout: 1000, }); </style> <body> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#"><img class="img-logo" src="img/logo.png"></a> </div> <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav navbar-right"> <form action="{{route('logout')}}" method="post"> {!!csrf_field()!!} #if(!empty(Auth::user()->image)) <img src="{{ Auth::user()->image }}" class="avatar" alt="" width="60" height="60"> #else <img src={{ url('uploads/avatar.png') }} class="avatar" alt="" width="60" height="60"> #endif <b>Your Driver of the Day, {{ Auth::user()->name }}</b> <button class="btn btn-danger">Log out</button> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Route/Bus Details </button> </form> </ul> </div> </div> </nav> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Select Your Desire Route</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <form action="{{ route('surveysubmit') }}" > <div class="form-group"> <h4>Select Bus</h4> <select onchange="$('#busid').val(this.value);" class="form-control" > #php $display=''; $initbusid = ''; $buses = Bus::where(['archive'=>1])->orderBy('id')->get(['id','busplate']); foreach($buses as $bus){ if(empty($initbusid)){$initbusid=$bus->id;} $display .= '<option value='.$bus->id.'>'.$bus->busplate.'</option>'; } echo $display; #endphp </select> </div> <div class="form-group"> <h4>Select Route</h4> <select onchange="$('#routeid').val(this.value);" class="form-control" > #php $display2=''; $initrouteid = ''; $bgcroutes = Bgcroute::where(['routeloc'=>1,'archive'=>1])->orderBy('id')->get(['id','bgcbusroute']); foreach($bgcroutes as $bgcroute){ if(empty($initrouteid)){$initrouteid=$bgcroute->id;} $display2 .= '<option value='.$bgcroute->id.'>'.$bgcroute->bgcbusroute.'</option>'; } echo $display2; #endphp </select> </div> <button type="button" class="btn btn-danger" data-dismiss="modal">Start Survey</button> </form> </div> </div> </div> </div> #php $questions = Surveyquestion::where('status',1)->get(['squestions','id'])->first(); #endphp <section class="testimonials"></section> <div class="jumbotron visible-xs-block visible-sm-block visible-md-block visible-lg-block hero-technology"> <h2 class="bg-success hero-title">{{ $questions->squestions }}</h2> <p class="visible-xs-block visible-sm-block visible-md-block visible-lg-block visible-xs-inline visible-sm-inline visible-md-inline visible-lg-inline visible-xs-inline-block visible-sm-inline-block visible-md-inline-block visible-lg-inline-block hidden-xs hidden-sm hidden-md hidden-lg hero-subtitle">Nullam id dolor id nibh ultricies vehicula ut id elit. Cras justo odio, dapibus ac facilisis in, egestas eget quam.</p> <p class="text-primary bg-warning">Help Us Serve You Better</p> <p></p> <p class="text-center bg-primary">Rate us. Choose a smiley that Corresponds to your riding experience</p> <div> <input type="hidden" name="driverid" id="driverid" value="{{ Auth::user()->id }}"/> <input type="hidden" name="busid" id="busid" value="{{ $initbusid }}"/> <input type="hidden" name="routeid" id="routeid" value="{{ $initrouteid }}"/> <input type="hidden" name="questionid" id="questionid" value="{{ $questions->id }}"/> <input type="hidden" name="responseid" id="responseid"/> <table class="table"> <thead> <tr> <th class="info visible-xs-block visible-sm-block visible-md-block visible-lg-block visible-xs-inline visible-sm-inline visible-md-inline visible-lg-inline visible-xs-inline-block"> <img class="img-rounded" src="assets/img/person-clipart-silhouette-blue-14518-blue-man-design.png" height="100"> <img src="assets/img/inlove.gif" height="70" id="loveid"> <img src="assets/img/like.gif" height="90" id="likeid"> <img src="assets/img/facepalm.gif" height="70" id="faceid"> <img src="assets/img/cry.gif" height="70" id="cryid"> </th> <th class="danger visible-xs-block visible-sm-block visible-md-block visible-lg-block visible-xs-inline visible-sm-inline visible-md-inline visible-lg-inline visible-xs-inline-block"> <img class="img-rounded" src="assets/img/pink-female-symbol-190136.png" width="40" height="100"> <img src="assets/img/inlove.gif" height="70" id="loveid2"> <img src="assets/img/like.gif" height="90" id="likeid2"> <img src="assets/img/facepalm.gif" height="70" id="faceid2"> <img src="assets/img/cry.gif" height="70" id="cryid2"> </th> </tr> </thead> <tbody> <tr></tr> <tr></tr> </tbody> <caption> </caption> </table> </div> <p>For Comments/Feedback Email us at bgc#bgc.com</p> </div> <div class="container"> <div class="table-responsive"> <table class="table"> <thead> <tr></tr> </thead> <tbody> <tr></tr> <tr></tr> </tbody> </table> </div> </div> <script src="assets/js/jquery.min.js"></script> <script src="assets/bootstrap/js/bootstrap.min.js"></script> <script type="text/javascript"> $(document).ready(function(e){ }); function surveyvote(){ driverid = $('#driverid').val(); busid = $('#busid').val(); routeid = $('#routeid').val(); questionid = $('#questionid').val(); responseid = $('#responseid').val(); $.ajax({ "type":"get", "url": "{{ route('surveyvoting') }}", "data": '&driverid='+driverid+'&busid='+busid+'&routeid='+routeid+'&questionid='+questionid+'&responseid='+responseid, "success":function(result){ // Do something you want! swal({ title: 'Thank You!', //text: 'I will close in 3 seconds.', timer: 1000, onOpen: () => { swal.showLoading() } }).then((result) => { if ( // Read more about handling dismissals result.dismiss === swal.DismissReason.timer ) { console.log('I was closed by the timer') } }) } }); } </script> <script type="text/javascript"> var screenSaver = {}; function startScreenSaver(options) { //* attach event listeners to exit screensaver attachScreenSaverEventListeners(); if(!screenSaver.initiated) { //* set screensaver options screenSaver.options = { timeout: options.timeout || 5000, //* default timer to start screensaver is 10 minutes width: options.width || 25, //* default width is 25rem height: options.height || 25, //* default height is 25rem exitTimeout: options.exitTimeout || null, //* default timer to exit screensaver is disabled } //* create elements var overlay = document.createElement("div"); overlay.setAttribute('class', 'screensaver-overlay'); document.body.appendChild(overlay); var createBadge = document.createElement("div"); createBadge.setAttribute('id', 'saver-badge'); document.body.appendChild(createBadge); createBadge.style.width = screenSaver.options.width + 'rem'; createBadge.style.height = screenSaver.options.height + 'rem'; } document.getElementsByTagName("body")[0].classList.remove('screensaver'); screenSaver.initiated = true; screenSaver.setTimeoutValue = screenSaver.options.timeout; screenSaver.setTimeoutExit = screenSaver.options.timeoutExit; screenSaver.setTimeout = null; //* clear timeout screenSaver.inProgress = false; screenSaver.timerStarted = false; clearTimeout(screenSaver.setTimeout); screenSaver.setTimeout = setTimeout(function() { document.getElementsByTagName("body")[0].classList.add('screensaver'); screenSaver.inProgress = true; var saverBadge = document.getElementById("saver-badge"); clearInterval(screenSaver.setInterval); //* clear badge display interval screenSaver.setInterval = null; //* get dimensions in em var windowHeight = window.outerHeight / parseFloat(window.getComputedStyle(document.getElementsByTagName("body")[0], null).getPropertyValue('font-size')); var windowWidth = window.outerWidth / parseFloat(window.getComputedStyle(document.getElementsByTagName("body")[0], null).getPropertyValue('font-size')); screenSaver.setInterval = setInterval(function() { if (screenSaver.inProgress === true) { saverBadge.classList.remove('visible'); setTimeout(function() { saverBadge.offsetWidth = saverBadge.offsetWidth; saverBadge.classList.add('visible'); },1); var saverTopValue = Math.floor(Math.random() * windowHeight) - screenSaver.options.width; var saverLeftValue = Math.floor(Math.random() * windowWidth) - screenSaver.options.height; if (saverTopValue <= 0) { //* make sure the badge doesn't go off the screen saverTopValue = saverTopValue + 15; } if (saverLeftValue <= 0) { saverLeftValue = saverLeftValue + 15; } saverBadge.style.top = saverTopValue + 'rem'; saverBadge.style.left = saverLeftValue + 'rem'; if(screenSaver.timerStarted === false && screenSaver.options.exitTimeout != null) { startScreenSaverTimer(); } } }, 6000); }, screenSaver.setTimeoutValue); } function startScreenSaverTimer() { screenSaver.timerStarted = true; setTimeout(function() { stopScreenSaver(); }, screenSaver.setTimeoutExit); } function stopScreenSaver() { startScreenSaver(); clearInterval(screenSaver.setInterval); document.getElementsByTagName("body")[0].classList.remove('screensaver'); screenSaver.timerStarted = false; } function attachScreenSaverEventListeners() { var events = ['touchstart', 'mousedown', 'mousemove', 'touchmove', 'keypress', 'scroll']; var resetScreenSaver = function(e) { if (screenSaver.inProgress) { e.stopPropagation(); e.preventDefault(); } clearTimeout(screenSaver.setTimeout); clearInterval(screenSaver.setInterval); document.getElementsByTagName("body")[0].classList.remove('screensaver'); startScreenSaver(); } var checkClick = function(e) { if (screenSaver.inProgress) { startScreenSaver(); } } var bindEvents = function(eventName) { document.addEventListener(eventName, screenSaver.initialize); //* bind click as fallback for touchstart and mousedown document.addEventListener('click', checkClick); } var unbindEvents = function(eventName) { document.removeEventListener(eventName, screenSaver.initialize); } } </script> </body> </html> Here is the related files that I think that is related on the script or the javascript css file screensaver.css body.screensaver #saver-badge { opacity: 0; display: block; position: absolute; filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=12, OffY=12,Color='#444')"; filter: url(#drop-shadow); -webkit-filter: drop-shadow(12px 12px 20px rgba(0,0,0,0.5)); filter: drop-shadow(12px 12px 20px rgba(0,0,0,0.5)); background: url(../img/vwd.png) center; background-size: contain; z-index: 1001; } body.screensaver #saver-badge.visible { -webkit-animation: fadeBadge 6s; -moz-animation: fadeBadge 6s; -o-animation: fadeBadge 6s; animation: fadeBadge 6s; opacity: 1; } body.screensaver .screensaver-overlay { background: #000; opacity: .5; position: fixed; top: 0; bottom: 0; right: 0; left: 0; z-index: 1000; } #saver-badge { display: none; } #-webkit-keyframes fadeBadge { 0% { opacity: 0; } 20% { opacity: 1; } 80% { opacity: 1; } 100% { opacity: 0; } } #-moz-keyframes fadeBadge { 0% { opacity: 0; } 20% { opacity: 1; } 80% { opacity: 1; } 100% { opacity: 0; } } #-o-keyframes fadeBadge { 0% { opacity: 0; } 20% { opacity: 1; } 80% { opacity: 1; } 100% { opacity: 0; } } #keyframes fadeBadge { 0% { opacity: 0; } 20% { opacity: 1; } 80% { opacity: 1; } 100% { opacity: 0; } } js file screensaver.js var screenSaver = {}; function startScreenSaver(options) { //* attach event listeners to exit screensaver attachScreenSaverEventListeners(); if(!screenSaver.initiated) { //* set screensaver options screenSaver.options = { timeout: options.timeout || 60000, //* default timer to start screensaver is 10 minutes width: options.width || 25, //* default width is 25rem height: options.height || 25, //* default height is 25rem exitTimeout: options.exitTimeout || null, //* default timer to exit screensaver is disabled } //* create elements var overlay = document.createElement("div"); overlay.setAttribute('class', 'screensaver-overlay'); document.body.appendChild(overlay); var createBadge = document.createElement("div"); createBadge.setAttribute('id', 'saver-badge'); document.body.appendChild(createBadge); createBadge.style.width = screenSaver.options.width + 'rem'; createBadge.style.height = screenSaver.options.height + 'rem'; } document.getElementsByTagName("body")[0].classList.remove('screensaver'); screenSaver.initiated = true; screenSaver.setTimeoutValue = screenSaver.options.timeout; screenSaver.setTimeoutExit = screenSaver.options.timeoutExit; screenSaver.setTimeout = null; //* clear timeout screenSaver.inProgress = false; screenSaver.timerStarted = false; clearTimeout(screenSaver.setTimeout); screenSaver.setTimeout = setTimeout(function() { document.getElementsByTagName("body")[0].classList.add('screensaver'); screenSaver.inProgress = true; var saverBadge = document.getElementById("saver-badge"); clearInterval(screenSaver.setInterval); //* clear badge display interval screenSaver.setInterval = null; //* get dimensions in em var windowHeight = window.outerHeight / parseFloat(window.getComputedStyle(document.getElementsByTagName("body")[0], null).getPropertyValue('font-size')); var windowWidth = window.outerWidth / parseFloat(window.getComputedStyle(document.getElementsByTagName("body")[0], null).getPropertyValue('font-size')); screenSaver.setInterval = setInterval(function() { if (screenSaver.inProgress === true) { saverBadge.classList.remove('visible'); setTimeout(function() { saverBadge.offsetWidth = saverBadge.offsetWidth; saverBadge.classList.add('visible'); },1); var saverTopValue = Math.floor(Math.random() * windowHeight) - screenSaver.options.width; var saverLeftValue = Math.floor(Math.random() * windowWidth) - screenSaver.options.height; if (saverTopValue <= 0) { //* make sure the badge doesn't go off the screen saverTopValue = saverTopValue + 15; } if (saverLeftValue <= 0) { saverLeftValue = saverLeftValue + 15; } saverBadge.style.top = saverTopValue + 'rem'; saverBadge.style.left = saverLeftValue + 'rem'; if(screenSaver.timerStarted === false && screenSaver.options.exitTimeout != null) { startScreenSaverTimer(); } } }, 6000); }, screenSaver.setTimeoutValue); } function startScreenSaverTimer() { screenSaver.timerStarted = true; setTimeout(function() { stopScreenSaver(); }, screenSaver.setTimeoutExit); } function stopScreenSaver() { startScreenSaver(); clearInterval(screenSaver.setInterval); document.getElementsByTagName("body")[0].classList.remove('screensaver'); screenSaver.timerStarted = false; } function attachScreenSaverEventListeners() { var events = ['touchstart', 'mousedown', 'mousemove', 'touchmove', 'keypress', 'scroll']; var resetScreenSaver = function(e) { if (screenSaver.inProgress) { e.stopPropagation(); e.preventDefault(); } clearTimeout(screenSaver.setTimeout); clearInterval(screenSaver.setInterval); document.getElementsByTagName("body")[0].classList.remove('screensaver'); startScreenSaver(); } var checkClick = function(e) { if (screenSaver.inProgress) { startScreenSaver(); } } var bindEvents = function(eventName) { document.addEventListener(eventName, screenSaver.initialize); //* bind click as fallback for touchstart and mousedown document.addEventListener('click', checkClick); } var unbindEvents = function(eventName) { document.removeEventListener(eventName, screenSaver.initialize); } for (var i=0;i<events.length;i++) { bindEvents(events[i]); } }
Add a fade in on images loaded by JavaScript
I have a simple function to replace one image with others using JavaScript. And I have one line to fade in it when loading. But how can I add a fade in when the new image is displayed? <script type="text/javascript"> function changeImage(a) { document.getElementById("Image").src = a; } </script> <div> <img src="Mini-01.jpg" onclick="changeImage('Photo-01.jpg');"> <img src="Mini-02.jpg" onclick="changeImage('Photo-02.jpg');"> </div> <div> <img id="Image" src="Photo-01.jpg" onload="this.style.animation='fadein 2s'"> </div> I tried using: onchange="this.style.animation='fadein 2s'" but it does not work. I think it is too simple to use Jquery on this case. Can you please helm me?
You can achieve the desired using css3 like this on changeImage() function. #keyframes fadeIn { from { opacity:0; } to { opacity:1; } } .container { top: 20%; left: 20%;} .fade-in { animation:fadeIn ease-in 1; animation-duration:5s; } <script type="text/javascript"> function changeImage(a) { var elm = document.getElementById("Image"); var clonedElm = elm.cloneNode(true); elm.parentNode.replaceChild(clonedElm, elm); document.getElementById("Image").src = a; } </script> <div> <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/3c/Perkin_Warbeck.jpg/200px-Perkin_Warbeck.jpg" onclick="changeImage('https://upload.wikimedia.org/wikipedia/commons/thumb/3/3c/Perkin_Warbeck.jpg/200px-Perkin_Warbeck.jpg');"> <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/9/97/Leonard_Cohen_2008.jpg/200px-Leonard_Cohen_2008.jpg" onclick="changeImage('https://upload.wikimedia.org/wikipedia/commons/thumb/9/97/Leonard_Cohen_2008.jpg/200px-Leonard_Cohen_2008.jpg');"> </div> <div class="container"> <img id="Image" src="" class="fade-in"> </div>
You can write custom function for fadeIn like this: function fadeIn(el) { el.style.opacity = 0; var tick = function() { el.style.opacity = +el.style.opacity + 0.01; if (+el.style.opacity < 1) { (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16) } }; tick(); } //taken from http://stackoverflow.com/questions/23244338/pure-javascript-fade-in-function function changeImage(a) { var el = document.getElementById("Image"); el.src = a; fadeIn(el) } where el = document.getElementById() or something. Here is https://jsfiddle.net/60x3bo8f/2/
giving fideIn fadeOut effect on changing the image src
I was working with responsive web design and I wanted to slide some images in to a page. I tried some plugins but the problem with the plugin is it uses width and height property and also assigns position: absolute. So I thought of changing the src of the image myself using js and it worked fine, but can I give some transition effect to it? Demo fiddle What I have done is: var i = 0; var total = 2; window.setInterval(function() { show_hide(); }, 1000); function show_hide() { var img = $('.image-holder img, .image-holder2 img'); //alert(img.length); if (i % 2 == 0) { img[0].src = 'http://digimind.com/blog/wp-content/uploads/2012/02/number2c.png'; img[1].src = 'http://digimind.com/blog/wp-content/uploads/2012/02/number2c.png'; i = 0; } else { img[0].src = 'http://healthystartups.com/storage/600px-MA_Route_1.png?__SQUARESPACE_CACHEVERSION=1319542839834'; img[1].src = 'http://healthystartups.com/storage/600px-MA_Route_1.png?__SQUARESPACE_CACHEVERSION=1319542839834'; } i++; } My HTML is as follows: <div class="image-holder" > <img src="http://healthystartups.com/storage/600px-MA_Route_1.png?__SQUARESPACE_CACHEVERSION=1319542839834" /> </div> <div class="image-holder2" > <img src="http://healthystartups.com/storage/600px-MA_Route_1.png?__SQUARESPACE_CACHEVERSION=1319542839834" /> </div>
Here's what I put together. jsFiddle javascript var img = $(".image-holder img") var i = 0; var count = img.length - 1; setInterval(function() { showImage(i); i++; if (i > count) i = 0; }, 2000); function showImage(i) { img.eq(i - 1).animate({ "opacity": "0" }, 1000); img.eq(i).animate({ "opacity": "1" }, 1000); } HTML <div class="image-holder" > <img src="http://healthystartups.com/storage/600px-MA_Route_1.png?__SQUARESPACE_CACHEVERSION=1319542839834" /> </div> <div class="image-holder" > <img src="http://digimind.com/blog/wp-content/uploads/2012/02/number2c.png" /> </div> CSS .image-holder img{ opacity: 0;} .image-holder { position: absolute; }