Modal close clicking outside the content - javascript

Can someone please help me? I need to be able to close this modal when I click outside the content; this is my code:
$(document).ready(function(){
$(".add-roles-btn").click(function(){
$("#modal1").addClass("show-modal");
});
});
.overlay {
height: 100vh;
width: 100%;
position: fixed;
top: 0;
left: 0;
background-color: rgba(50, 65, 97, 0.5);
z-index: 9999;
opacity: 0;
visibility: hidden;
transition: all .3s; }
.overlay .cancel {
position: absolute;
width: 100%;
height: 100%;
cursor: default; }
.overlay__content {
position: absolute;
top: 44%;
left: 55.5%;
padding: 4.8rem 6.4rem;
width: 540px;
background-color: #ffffff;
box-shadow: 0 2rem 4rem rgba(81, 136, 255, 0.2);
border-radius: 3px;
display: table;
overflow: hidden;
opacity: 0;
transform: translate(-50%, -50%) scale(0.25);
transition: all .4s .2s; }
#media only screen and (max-width: 61.875em) {
.overlay__content {
top: 50%;
left: 50%; } }
#media only screen and (max-width: 47em) {
.overlay__content {
padding: 4rem 6.5rem;
width: 500px; } }
#media only screen and (max-width: 37.5em) {
.overlay__content {
padding: 4rem 6.5rem;
width: 100%; } }
.show-modal {
opacity: 1;
visibility: visible; }
.show-modal .overlay__content {
opacity: 1;
transform: translate(-50%, -50%) scale(1); }
<button type="button" class="add-roles-btn"><i class="material-icons icon--middle icon--pr-8">add</i>Add roles</button>
<!-- Pop up modal -->
<div class="overlay" id="modal1">
<div class="overlay__content">
<h3 class="heading-primary">Add role</h3>
<form action="#">
<div class="form__group">
<input type="text" class="form__input" id="role_title">
<label for="role_title" class="form__label">Role Title</label>
</div>
<div class="form__group">
<textarea name="" class="form__input resize-none u-margin-bottom-0" id="role_description" rows="5"></textarea>
<label for="role_description" class="form__label">Role Description</label>
</div>
<div class="align-right">
<button class="btn btn--primary capitalize add-role-btn">Add Role <i class="material-icons icon--sub add-modal-role">add</i></button>
</div>
</form>
</div>
</div>
<!-- Pop up modal -->
As you can see it has the JS code on click it shows the modal, but I am not able to change it when you click outside to be closed; how can this be done? I have created this from scratch. I do not want to use some library or something; can you help me? I am new on JavaScript and coding on general. I would really appreciate it; thank you.

Here is the updated code, basically the concept was listening to click events on the body and if the DOM parent chain on the element doesn't reach the modal modal1 - the click is outside of it and therefore the modal can be closed.
Another important note was calling e.stopPropagation as the body event would be called after the button event, causing the window to be closed. Calling e.stopPropgation would mean that when the button is clicked, the "larger" body event won't trigger.
$(document).ready(function(){
$(".add-roles-btn").click(function(e){
$("#modal1").addClass("show-modal");
// This is required so that when clicking the button the click event wont propogate to the body event
e.stopPropagation()
});
// This function listens to all clicks on the document and gets the event data e
$('body').click(function(e) {
target = e.target;
// If the clicked target isnt under modal1 - that means it won't be found in its parents
if (($(target)).parents('#modal1').length == 0) {
$("#modal1").removeClass("show-modal");
}
})
});
$(document).ready(function(){
$(".add-roles-btn").click(function(e){
$("#modal1").addClass("show-modal");
// This is required so that when clicking the button the click event wont propogate to the body event
e.stopPropagation()
});
// This function listens to all clicks on the document and gets the event data e
$('body').click(function(e) {
target = e.target;
// If the clicked target isnt under modal1 - that means it won't be found in its parents
if (($(target)).parents('#modal1').length == 0) {
$("#modal1").removeClass("show-modal");
}
})
});
.overlay {
height: 100vh;
width: 100%;
position: fixed;
top: 0;
left: 0;
background-color: rgba(50, 65, 97, 0.5);
z-index: 9999;
opacity: 0;
visibility: hidden;
transition: all .3s; }
.overlay .cancel {
position: absolute;
width: 100%;
height: 100%;
cursor: default; }
.overlay__content {
position: absolute;
top: 44%;
left: 55.5%;
padding: 4.8rem 6.4rem;
width: 540px;
background-color: #ffffff;
box-shadow: 0 2rem 4rem rgba(81, 136, 255, 0.2);
border-radius: 3px;
display: table;
overflow: hidden;
opacity: 0;
transform: translate(-50%, -50%) scale(0.25);
transition: all .4s .2s; }
#media only screen and (max-width: 61.875em) {
.overlay__content {
top: 50%;
left: 50%; } }
#media only screen and (max-width: 47em) {
.overlay__content {
padding: 4rem 6.5rem;
width: 500px; } }
#media only screen and (max-width: 37.5em) {
.overlay__content {
padding: 4rem 6.5rem;
width: 100%; } }
.show-modal {
opacity: 1;
visibility: visible; }
.show-modal .overlay__content {
opacity: 1;
transform: translate(-50%, -50%) scale(1); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="add-roles-btn"><i class="material-icons icon--middle icon--pr-8">add</i>Add roles</button>
<!-- Pop up modal -->
<div class="overlay" id="modal1">
<div class="overlay__content">
<h3 class="heading-primary">Add role</h3>
<form action="#">
<div class="form__group">
<input type="text" class="form__input" id="role_title">
<label for="role_title" class="form__label">Role Title</label>
</div>
<div class="form__group">
<textarea name="" class="form__input resize-none u-margin-bottom-0" id="role_description" rows="5"></textarea>
<label for="role_description" class="form__label">Role Description</label>
</div>
<div class="align-right">
<button class="btn btn--primary capitalize add-role-btn">Add Role <i class="material-icons icon--sub add-modal-role">add</i></button>
</div>
</form>
</div>
</div>
<!-- Pop up modal -->

You stated you don't want to use any library so here's a vanilla JS solution.
To provide that, I also "translated" your jQuery code to vanilla JS:
document.getElementsByClassName('add-roles-btn')[0].onclick = function() {
document.getElementById('modal1').classList.add('show-modal');
}
// This block hides the modal when the user clicks outside of it
window.onclick = function(event) {
if (event.target == document.getElementById('modal1')) {
document.getElementById('modal1').style.display = 'none';
}
}
Here's a working example with the rest of your code.
If you want the ability to re-open it, this should work:
var modal = document.getElementById('modal1');
document.getElementsByClassName('add-roles-btn')[0].onclick = function() {
modal.classList.add('show-modal');
}
window.onclick = function(event) {
if (event.target == modal) {
modal.classList.remove('show-modal');
}
}
Here's the updated code.

Related

Modal stops working after image changes on page

Im building an app where you can like and dislike movies. I have a database of movies and show each one to the user. When you click like or dislike it takes you to the next poster.
I also have access to the description and rating. I've added my own modal to show the user when clicked more information on that movie.
The problem Im having is the modal works for the first movie and changes the class to active. However on the second one it stops working. I can see in the inspector the modal code is there and has the correct information for that movie. But the modal seems to still not work/become unresponsive. Perhaps its an error that I've missed. I notice that it does add active once again on the first item. Perhaps I need to find a way to switch to the current movie instead or incorporate the modal into the slides more? or find a way to reset it..
EDIT -:
Adding to the above. Having done a bit more testing. It seems like the modal doesnt know what id the slide is on.. So it never knows when the slide is changed.. Any ideas how I would do this?
EDIT2 -:
I've now got it so every modal has a unique id per poster using the contact.id. Any way to link the modal id together with the slides so when I change the slide the modal knows and changes to active on the next slide?
const modalBtn = document.querySelectorAll(".modal-btn");
const modalBg = document.querySelectorAll("movie-modal");
const modalClose = document.querySelectorAll(".close-button");
const overlay = document.querySelectorAll("overlay");
const overlayClose = document.querySelectorAll("overlay");
const activeModal = document.querySelectorAll(".movie-modal:first-child")
modalBtn.forEach(function(btn, index){
btn.addEventListener('click', function(click) {
console.log(click)
modalBg.classList.add('active');
overlay.classList.add('active');
var content_id = activeModal.data("id");
console.log(content_id)
});
});
modalClose.forEach(function(btn, index){
btn.addEventListener('click', function(click) {
console.log(click)
modalBg.classList.remove('active');
overlay.classList.remove('active');
});
});
overlay.forEach(function(overlay, index){
overlay.addEventListener('click', function() {
overlayClose.classList.remove('active');
});
});
overlay.forEach(function(overlay, index){
overlay.addEventListener('click', function() {
const modals = document.querySelectorAll('.movie-modal.active')
modals.forEach(modal => {
modal.classList.remove('active');
overlay.classList.remove('active');
})
})
});
$(function(){
var $activeSlide = $('#slides .slide:first-child');
// show first slide
$activeSlide.addClass("active");
// on click event decline
$("#decline").on("click", function(){
goToSlide('decline');
});
// on click approve then what?
$("#approve").on("click", function(){
var content_id = $activeSlide.data("id");
console.log(content_id)
goToSlide('approve');
// $.ajax({
// url: "/user_contents/liked" + content_id,
// method: "post",
// dataType: "ajax"
// });
});
// adding the 'showing' or 'active' slide class to each element
function goToSlide(action) {
$activeSlide.removeClass("active");
$activeSlide = $activeSlide.next(".slide");
// send data to controller
if(action == "approve"){
console.log(action);
} else {
console.log('dislike');
}
$activeSlide.addClass("active");
}
});
.movie-modal {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%) scale(0);
transition: 200ms ease-in-out;
box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
border-radius: 10px;
z-index: 10;
background-color: white;
width: 300px;
max-width: 80%;
color: black;
}
.movie-modal.active{
transform: translate(-50%, -50%) scale(1);
}
.movie-modal-header {
padding: 8px 16px;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid rgb(182, 182, 182);
}
.movie-rating {
font-size: 1.25rem;
font-weight: bold;
}
.close-button {
cursor: pointer;
border: none;
outline: none;
background: none;
font-size: 1.25rem;
font-weight: bold;
}
.movie-modal-body {
padding: 16px;
color: rgb(160, 160, 160);
}
#overlay {
position: fixed;
opacity: 0;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.35);
pointer-events: none;
transition: 200ms ease-in-out;
}
#overlay.active {
opacity: 1;
pointer-events: all;
}
#slides {
position: relative;
height: 100%;
padding: 0px;
margin: 0 auto;
list-style-type: none;
}
.slide {
position: absolute;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
opacity: 0;
z-index: 1;
box-sizing: border-box;
color: #fff;
-webkit-transition: opacity 1s;
-moz-transition: opacity 1s;
-o-transition: opacity 1s;
transition: opacity 1s;
}
.showing {
opacity: 1;
z-index: 2;
}
#slide-controls {
margin: 20px 0 400px;
width: 100%;
position: absolute;
display: flex;
justify-content: center;
justify-content: space-between;
z-index: 10;
color: #ffffffba;
font-size: 24px;
top: 50%;
}
.image-carousel {
width: 100%;
height: 642px;
margin: 0 auto;
background-size: contain;
background-repeat: no-repeat;
position: relative;
}
#decline {
margin-left: 16px;
}
#approve {
margin-right: 16px;
}
.img-thumbnail {
padding: 0 !important;
}
<ul id="slides">
<% #contents.each_with_index do |content, i| %>
<li class="slide <%= 'active' if i == 0 %>" data-id="<%= content.id %>">
<div class="image-carousel" style="background-image: url('<%= content.poster %>')">
</div>
<button class="modal-btn">Open Modal</button>
<div id="movie-modal <%= content.id %>" class="movie-modal">
<div class="movie-modal-header">
<div class="movie-rating" style="">Average rating: <strong><%= content.rating %></strong></div>
<button class="close-button">×</button>
</div>
<div class="movie-modal-body"><p><%= content.description %></p></div>
</div>
<div id="overlay <%= content.id %>"></div>
</li>
<% end %>
</ul>
<div id="slide-controls">
<span id="decline"><i class="fa fa-solid fa-thumbs-down fa-2x"></i></span>
<span id="approve"><i class="fa fa-solid fa-thumbs-up fa-2x"></i></span>
</div>
This shows when the first poster is clicked the modal works and movie-modal active is added to the modal class
The second image with Morbius in it.. The modal class doesnt change for the current slide showing however it changes for the previous slide.. BUT the previous slide only changes once and then sticks to active. Nothing is shown on the poster.

How to get more toggle hide/show div with different class

I have a toggle that show or hide a div class. The status toggle is saved in local storage, so after page refresh the desired setting is maintained.
Now I'm trying to get another toggle that performs the same functions on a different class. I tried with a simple copy / paste changing the names of the classes and functions, but it doesn't work.
Can anyone give me a suggestion?
Fiddle: https://jsfiddle.net/snake93/s0rx4ube/9/
function save() {
var checkbox = document.getElementById("ck1");
localStorage.setItem("ck1", JSON.stringify(checkbox.checked));
}
function isChecked(isOn) {
if (isOn === true) {
$(".hideme").show();
} else {
$(".hideme").hide();
}
}
//for loading
var checked = JSON.parse(localStorage.getItem("ck1"));
document.getElementById("ck1").checked = checked;
console.log(checked);
$(document).ready(function(){
isChecked(checked)
$(".switch input").on("change", function(e) {
const isOn = e.currentTarget.checked;
console.log(isOn)
isChecked(isOn);
});
});
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider {
background-color: #2196F3;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
/*END OF TOGGLE SWITCH*/
.hideme {
padding:20px;
background: blue;
color: white;
font-weight: 800;
text-align: center;
}
<!-- jQuery -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<label class="switch">
<input type="checkbox" id="ck1" onchange="save()">
<span class="slider round hide-off"></span>
</label>
<br><br>
<div class="hideme">Please hide me, but bring me back later ;-)</div>
I believe you can have more dynamism by making better use of css selectors and adding an attribute with the same input id to the divs you intend to show/hide.
HTML:
<label class="switch">
<input type="checkbox" id="ck1">
<span class="slider round hide-off"></span>
</label>
<br><br>
<label class="switch">
<input type="checkbox" id="ck2">
<span class="slider round hide-off"></span>
</label>
<br><br>
<div class="hideme" id="label-ck1">Please hide me...</div>
<div class="hideme" id="label-ck2">Please hide me...</div>
JAVASCRIPT
$(document).ready(function(){
getLocalStatus()
$(".switch input").on("change", function(e) {
const element = e.currentTarget;
saveStatus(element)
setLabelVisibility(element.getAttribute('id'),element.checked);
})
})
function getLocalStatus() {
const checkboxes = $('input[type=checkbox]');
checkboxes.each(function(index,checkbox){
const checkboxId = checkbox.getAttribute('id')
var currentStatus= localStorage.getItem(checkboxId)
if (currentStatus == "true") {
currentStatus = true;
} else {
currentStatus = false;
}
checkbox.checked = currentStatus;
setLabelVisibility(checkboxId, currentStatus)
})
}
function setLabelVisibility(id,status){
const label = $("#label-" + id + "");
if(status == false){
label.hide();
return;
}
label.show();
}
function saveStatus(e) {
localStorage.setItem(e.getAttribute('id'), e.checked)
}
You need to give your show/hide DIVs different IDs and pass those into the function. (this is just one of several ways)
The element you want to show/hide needs a unique ID so we can differentiate it from the others, so forget about using a class as a selector here. The toggle function takes two parameters, the element that called it and the element ID that gets toggled. In the HTML below, 'this' will refer to that specific checkbox when its clicked. '#div1' and '#div2' are the IDs of the elements to toggle.
I've added in your local storage bit.
function toggle(p, c){
if ($(p).prop("checked")){
$(c).show();
}else{
$(c).hide();
}
localStorage.setItem($(p).attr("id"), JSON.stringify($(p).prop("checked")));
}
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider {
background-color: #2196F3;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
/*END OF TOGGLE SWITCH*/
.hideme{
padding:20px;
background: blue;
color: white;
font-weight: 800;
text-align: center;
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="switch">
<input type="checkbox" id="ck1" onchange="toggle(this, '#div1')">
<span class="slider round hide-off"></span>
</label>
<label class="switch">
<input type="checkbox" id="ck2" onchange="toggle(this, '#div2')">
<span class="slider round hide-off"></span>
</label>
<br><br>
<div id="div1" class="hideme">Please hide me, but bring me back later ;-)</div>
<div id="div2" class="hideme">Please hide me, but bring me back later ;-)</div>
This is another possible solution and one that I would prefer:
Change the input as so:
<input type="checkbox" id="ck1" class="btn" data-toggle-id="#div1">
Then the javascript (with jquery) would look like this instead:
$('.btn').on('change', function(){
var $d = $($(this).attr('data-toggle-id'));
if ($(this).prop("checked")){
$d.show();
}else{
$d.hide();
}
});

How to revert toggle button using javascript

I am trying to create a toggle button. Here is the code: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_switch
In my javascript code - I read the 'checkbox' value. If the value is true then I add another div and this another div also has a close button. When the close button is hit, I remove this newly added div from the dom.
So far this all works fine.
I also want to toggle back the button. I am setting up the value to false with the following line:
document.getElementsByName("addUserConfirmation").checked = false;
It does set the value to false, but the toggle button still remain blue. How do I set it back to off?
Here is the code snippet:
function removeCardRevertToggleButton(button, container) {
var parentContainer = document.getElementById(container);
jQuery(parentContainer).children().remove();
document.getElementsByName("addConfirmation").checked = false;
}
<div class="boxStyle">
<span class="closeButton" requestid="" onclick="removeCardRevertToggleButton(this, "inviteContainerContext")">×</span>
</div>
Here is the jsfiddle:
https://jsfiddle.net/u9y2w8ev/15/
When close ('x') button is clicked, I want to switch the toggle button to off.
document.getElementsByName("addConfirmation") returns an array (Elements). You have to access an array element like this
document.getElementsByName("addUserConfirmation")[0].checked
function removeCardRevertToggleButton(button) {
document.getElementsByName("addUserConfirmation")[0].checked = false;
}
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked+.slider {
background-color: #2196F3;
}
input:focus+.slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked+.slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
<body>
<label class="switch">
<input type="checkbox" name="addUserConfirmation" checked>
<span class="slider round"></span>
</label>
<div class="boxStyle">
<span class="closeButton" onclick='removeCardRevertToggleButton(this)'>×
</span>
</div>
</body>
I have updated fiddle as https://jsfiddle.net/k086xnpd/
HTML Code:
<body>
<label class="switch">
<input type="checkbox" id="test" name="addUserConfirmation" checked>
<span class="slider round"></span>
</label>
<div class="boxStyle">
<span class="closeButton" onclick='removeCardRevertToggleButton(this)'>×
</span>
</div>
</body>
JS Code:
function removeCardRevertToggleButton(button) {
alert("Clicked, new value = " + button.checked);
//var parentContainer = document.getElementById(container);
//jQuery(parentContainer).children().remove();
document.getElementById("test").checked = false;
document.getElementById("test").addClass('slider:before');
}
Hoping that is what you were looking for :)

Changing background-image to sql image

Is there a way to set the background-image: url(--SET THIS--), to an sql picture?
I was thinking about somthing like this:
$img = $MysqliHandler->query(SELECT avatar FROM account WHERE username="'.$_SESSION['name'].'"';
And then somehow change the url to: '.base64_encode( $img[0]['avatar'] ).'
Right now I just have a simple change avatar function, but I want to save this to a specific "'.$_SESSION['name'].'", so that user always have that avatar, and are able to change it.
Should I use ajax, and then link the new image to another php, and run a update image sql function there?
$("#ChangeImg").click(function(e) {
$("#imageUpload").click();
});
function fasterPreview(uploader) {
if (uploader.files && uploader.files[0]) {
var reader = new FileReader();
reader.readAsDataURL(uploader.files[0]);
reader.onloadend = function(){
document.getElementById("imgDivEdit").style.backgroundImage = "url(" + reader.result + ")";
}
}
}
$("#imageUpload").change(function() {
fasterPreview(this);
});
#imageUpload {
display: none;
}
.container {
position: relative;
width: 125px;
height: 125px;
}
.overlay {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
height: 125px;
width: 125px;
opacity: 0;
transition: .5s ease;
background-color: rgba(11, 90, 180, 0.795);
border-radius: 50%;
}
.container:hover .overlay {
opacity: 0.7;
}
.text {
color: white;
font-size: 20px;
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
text-align: center;
cursor: pointer;
}
#imgDivEdit {
width: 125px;
height: 125px;
background-image: url("https://www.whatsappprofiledpimages.com/wp-content/uploads/2019/01/Nice-Whatsapp-DP-Profile-Images-4-300x300.jpg");
background-position: 5px -5px;
border-radius: 50%;
background-size: cover;
}
<div id="avatar"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div id="imgDivEdit"></div>
<div id="ChangeImg" class="overlay">
<div class="text">Change Image</div>
</div>
</div>
</div>
<input id="imageUpload" type="file" name="profile_photo" placeholder="Photo" required="" capture>
So I use data:image/jpeg;base64,'.$_SESSION['avatar'].', as background, in a separate .php file, and this is ofc. included in my .php file:
#imgDivEdit{
width: 125px;
height: 125px;
background-image: url("data:image/jpeg;base64,'.$_SESSION['avatar'].'");
border-radius: 50%;
background-size: cover;
}
Then I made a if statement, that updates the sql and then retrieve it and update session.
$URL = $_SERVER['REQUEST_URI'];
if(isset($_POST['Save']) && !empty($_POST['Save']))
{
if($_FILES["imageUpload"]["size"]>1010000 || $_FILES["imageUpload"]["size"]==0 )
{
echo"<h3 style='color:#db4409'>Failed to upload image.</h3>";
}
else{
$image=addslashes(file_get_contents($_FILES['imageUpload']['tmp_name']));
$sql='UPDATE accounts SET avatar = ("'.$image.'") WHERE username ='.$_SESSION['name'].'';
$query = $MysqliHandler->query($sql);
$sql='SELECT avatar FROM accounts WHERE username ='.$_SESSION['name'].'';
$avatar = $MysqliHandler->query($sql);
$_SESSION['avatar'] = base64_encode( $avatar[0]['avatar'] );
header("Refresh:0; url=$URL");
exit();
}
}
I made a save option to run all this when a image is uploaded, and showed:
<form method="POST" enctype="multipart/form-data">
<input id="imageUpload" type="file" name="imageUpload" placeholder="Photo" accept="image/x-png,image/gif,image/jpeg" required="" capture>
<div id="Change" hidden>
<input type="submit" name="Save" id="Save" value="Save" class="btn btn-info Save"/> <p style="font-size:11px;">Max size: 1Mb</p>
</div>
</form>
.js
$("#imageUpload").change(function() {
$("#Change").show();
});

Jquery animate() effect doesn't function well

When hover on the first and second element, some element will animate to the left, it works well if hovered with a normal speed, but will crashed if hovered too fast for some times
(the text won't show or the text won't move back to its original place when mouseoff, checkout the figures below).
Any suggestions would be appreciated.
1.text won't show
2.text won't move back to its original place
$(document).ready(function() {
var flag = false;
$(".tab-ico").hover(function() {
var f = $(this);
f.data('timeout', window.setTimeout(function() {
f.find(".tab-text").stop(true, true).animate({
left: "-=64"
}, 300, function() {
flag = true;
});
}, 300));
}, function() {
clearTimeout($(this).data("timeout"));
if (flag === true) {
$(this).find(".tab-text").stop(true, true).animate({
left: "+=64"
}, 300, function() {
flag = false;
});
}
});
});
.pfm-toolbar-wrap {
height: 100%;
position: fixed;
right: 0;
top: 0;
width: 35px;
z-index: 9990;
}
.pfm-tbar-tab-Spike {
position: relative;
width: 35px;
}
.pfm-toolbar-tabs {
border-right: 5px solid #7a6e6e;
height: 100%;
}
.p-tab div.tab-ico {
background: #7a6e6e;
}
.tab-text {
border-radius: 3px;
color: #fff;
height: 32px;
left: 0px;
line-height: 32px;
position: absolute;
text-align: center;
width: 70px;
padding-right: 5px;
z-index: -1;
background: #7a6e6e;
}
.tab-text a {
color: #fff;
display: block;
}
.p-tab {
left: 0;
margin-top: -100px;
position: absolute;
top: 50%;
width: 35px;
z-index: 9;
text-align: center;
}
.p-tab div.tab-ico:hover {
background: #e20531;
cursor: pointer;
}
.p-tab div.tab-ico:hover .tab-text {
background: #e20531;
}
.tab-ico {
width:35px;
height:35px;
margin-bottom:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="pfm-toolbar-wrap">
<div class="pfm-toolbar-tabs">
<div class="p-tab">
<div class="pfm-tbar-tab-Spike m_b15">
<div class="tab-ico cart"> <i class="cbl-icon"></i> <em class="tab-text"> text</em>
</div>
</div>
<div class="pfm-tbar-tab-group m_b15">
<div class="tab-ico "> <i class="cbl-icon"></i>
<em class="tab-text"> text2</em>
</div>
</div>
</div>
</div>
</div>
you can use css transition-delay property as follows:
transition-delay: 1s; /* delays for 1 second */
-webkit-transition-delay: 1s; /* for Safari & Chrome */
Find more info here.
I suggest that you use CSS transition, here are two links that will help you make that with less code and using CSS transition
https://css-tricks.com/almanac/properties/t/transition/
https://blog.alexmaccaw.com/css-transitions

Categories

Resources