Create a confirmation popup within the area of particular image - javascript

I have multiple images on my page which are getting created dynamically within a div when user upload the images. Each image is having its unique parent div. When user wants to delete an image, I want a delete confirmation within the limits of that particular div only (not over full body) which currently I am unable to achieve. Currently I do have like this - .
where as I want to show this pop up message only over that particular image, something like this -
Thanks.

By using JavaScript we can achieve it.
HTML Structure
<div class="img-wrapper">
<img src="/image.png">
<span class="edit" onclick="myFunction();">edit</span>
<div class="popup-option"></div>
</div>
JavaScript function
function myFunction(id){
var htm = "<div class='popup'>"+
"<button>Delete</button>"+
"<button>Cancel</button>"+
"</div>";
$('.popup-option').append(htm);
}
CSS
.img-wrapper{ /* make main wrapper position relative and add your style */
position: relative;
}
.popup{ /* popup will cover full width of that particular item*/
position : absolute;
left: 0;
right:0;
width :100%;
height:100%;
z-index: 999;
background:rgba(0,0,0,.8);
}

Try something like
function getPosition(element) {
var xPosition = 0;
var yPosition = 0;
while(element) {
xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
element = element.offsetParent;
}
return { x: xPosition, y: yPosition };
}
To get the position of the image then show the pop up in the same coords

Related

HTML full size div containing a draggable table

I'm not sure how to explain what I exactly want (which makes it really hard to google for as well), but I would like to create a table with each cell a specific width and height (let's say 40x40 pixels).
This table will be way larger than the viewport, so it would need some scrolling, but I don't want scrollbars (this part ain't a problem), but a way to drag the table around "behind the viewport".
To make it a bit more complex, I need to be able to center a specific cell and know which cell is centered too (although if I know for example that the table is on left: -520px; I can calculate what the situation is).
Long story short, I'm looking for something that looks and works like maps.google.com, but then with a table and cells instead of a canvas or divs.
What you're trying to achieve is relatively simple. You have a container div element with position: relative; overflow: hidden applied via CSS and the content set to position: absolute. For example:
<div class="wrapper">
<div class="content-grid">
... your grid HTML ...
</div>
</div>
You then need to set up some mouse/touch tracking javascript, you can find plenty of examples around Stack Overflow or Google, which monitors the position of the mouse at mousedown or touchstart events and then tests this repeatedly on an interval to see where the pointer is and update the content-grid top and left position, until mouseup or touchend.
You can make this animation smooth using CSS transition on left and top.
The tricky bit is calculating the position for the centre cell. For this I would recommend calculating a central zone, the size of your grid cells (i.e. 40x40) in the middle of your container element. Then checking if any grid cell is currently more than 1/4 inside that zone, and treating it as the "central" element.
Here is a basic example for position a cell within a grid within a wrapper: https://jsfiddle.net/tawt430e/1/
Hope that helps!
I was a bit disappointed to see the down votes of my question at first. I can imagine that stackoverflow has a lot of issues with new people just trying to get their code written here, but that's not what I asked.
Anyway, with the "you share the problem, you share the solution", mindset, I fixed the code with help of tw_hoff and it all works now. It even saves the coordinates in the local storage so this example HTML keeps you in the same position if you refresh the page. I added the two example images I used as well (store the left one as farm.png, the right one as tile.png, same directory as the html page).
The actual code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Game map demo</title>
<style>
body { margin: 0; padding: 0; }
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div id="map" style="position: absolute; overflow: hidden; width: 100%; height: 100%; background-color: darkgreen;">
<div id="content" style="white-space: nowrap;">
</div>
</div>
<script>
for(i = 0; i < 20; i++) {
for(j = 0; j < 20; j++) {
var tile;
if((i == 4 || i == 5) && (j == 2 || j == 3)) {
tile = 'farm';
} else {
tile = 'tile';
}
$("#content").append('<div style="background: url(\'' + tile + '.png\'); width: 128px; height: 128px; position: absolute; margin-left: ' + (i * 128) + 'px; margin-top: ' + (j * 128) + 'px;"></div>');
}
}
$("body").css("-webkit-user-select","none");
$("body").css("-moz-user-select","none");
$("body").css("-ms-user-select","none");
$("body").css("-o-user-select","none");
$("body").css("user-select","none");
var down = false;
var current_left = 0;
var current_top = 0;
if(localStorage.getItem("current_left") && localStorage.getItem("current_top")) {
current_left = Number(localStorage.getItem("current_left"));
current_top = Number(localStorage.getItem("current_top"));
console.log(current_left);
$("#content").css('marginLeft', (current_left) + 'px');
$("#content").css('marginTop', (current_top) + 'px');
}
$(document).mousedown(function() {
down = true;
}).mouseup(function() {
down = false;
});
var cache_pageX;
var cache_pageY;
$( "#map" ).mousemove(function( event ) {
if(down == true) {
current_left += (-1 * (cache_pageX - event.pageX));
if(current_left > 0)
current_left = 0;
if(current_left < (-2560 + $("#map").width()))
current_left = (-2560 + $("#map").width());
current_top += (-1 * (cache_pageY - event.pageY));
if(current_top > 0)
current_top = 0;
if(current_top < (-2560 + $("#map").height()))
current_top = (-2560 + $("#map").height());
localStorage.setItem("current_left", current_left);
localStorage.setItem("current_top", current_top);
$("#content").css('marginLeft', (current_left) + 'px');
$("#content").css('marginTop', (current_top) + 'px');
}
cache_pageX = event.pageX;
cache_pageY = event.pageY;
});
</script>
</body>
</html>
It still needs some work, and of course a lot of work to be actually used in a game, but this part works and I hope if someone else ever might have the same issue and searches for it on stackoverflow my solutions gives them a push in the right direction :).
Thanks for those that helped!

Two instances of same popup div at cursor location

On a webpage, I have an image. When I mouseover it, a hidden div pops up at cursor location with information on that image. Clicking on that image, creates another one in another div. The new image also share the same div pop up when mouseover.
For the original image I use jquery.
$("#" + abys).on("mouseover", function(e){
$("#" + abys + "_tooltip").css({
left: e.pageX,
top: e.pageY
}).show();
});
$("#" + abys).on("mouseout", function(e){
$("#" + abys + "_tooltip").hide();
});
For the new image when clicked, I use pure javascript.
var itemDiv = document.getElementById("items_div");
var newImg = document.createElement("img");
newImg.src = "/items_img/" + abys + ".png";
newImg.id = abys + "_slot";
itemDiv.appendChild(newImg);
appendNum++;
console.log(appendNum);
newImg.onclick = function(){
newImg.parentNode.removeChild(newImg);
appendNum--;
console.log(appendNum);
}
newImg.onmouseover = function(e){
abysTooltip.style.display = "block";
abysTooltip.style.top = e.pageX;
abysTooltip.style.left = e.pageY;
}
CSS for the popup div.
.item_tooltip_div {
border:1px solid;
padding:20px;
width:400px;
display:none;
position:absolute;
z-index:10;
background-color:rgb(0,0,0);
pointer-events:none;
}
The issue I am running into is that when I mouseover the new image, the tooltip shows up at the original image location, and not my mouse cursor position.
Solved it by using jquery for both instances.
For some reason, jquery .css() was blocking javascript's .style. When hovering over the original image, the tooltip's top and left position is already set. When hovering over the new image, the top and left position did not change.

Show a series of images on scroll

The closest solution I found is Show div on scrollDown after 800px.
I'm learning HTML, CSS, and JS, and I decided to try to make a digital flipbook: a simple animation that would play (ie, load frame after frame) on the user's scroll.
I figured I would add all the images to the HTML and then use CSS to "stack them" in the same position, then use JS or jQuery to fade one into the next at different points in the scroll (ie, increasing pixel distances from the top of the page).
Unfortunately, I can't produce the behavior I'm looking for.
HTML (just all the frames of the animation):
<img class="frame" id="frame0" src="images/hand.jpg">
<img class="frame" id="frame1" src="images/frame_0_delay-0.13s.gif">
CSS:
body {
height: 10000px;
}
.frame {
display: block;
position: fixed;
top: 0px;
z-index: 1;
transition: all 1s;
}
#hand0 {
padding: 55px 155px 55px 155px;
background-color: white;
}
.frameHide {
opacity: 0;
left: -100%;
}
.frameShow {
opacity: 1;
left: 0;
}
JS:
frame0 = document.getElementById("frame0");
var myScrollFunc = function() {
var y = window.scrollY;
if (y >= 800) {
frame0.className = "frameShow"
} else {
frame0.className = "frameHide"
}
};
window.addEventListener("scroll", myScrollFunc);
};
One of your bigger problems is that setting frame0.className = "frameShow" removes your initial class frame, which will remove a bunch of properties. To fix this, at least in a simple way, we can do frame0.className = "frame frameShow", etc. Another issue is that frame0 is rendered behind frame1, which could be fixed a variety of ways. ie. Putting frame0's <img> after frame1, or setting frame0's CSS to have a z-index:2;, and then setting frame0's class to class="frame frameHide" so it doesn't show up to begin with. I also removed the margin and padding from the body using CSS, as it disturbs the location of the images. I have made your code work the way I understand you wanted it to, here is a JSFiddle.
It depends on your case, for example, in this jsFiddle 1 I'm showing the next (or previous) frame depending on the value of the vertical scroll full window.
So for my case the code is:
var jQ = $.noConflict(),
frames = jQ('.frame'),
win = jQ(window),
// this is very important to be calculated correctly in order to get it work right
// the idea here is to calculate the available amount of scrolling space until the
// scrollbar hits the bottom of the window, and then divide it by number of frames
steps = Math.floor((jQ(document).height() - win.height()) / frames.length),
// start the index by 1 since the first frame is already shown
index = 1;
win.on('scroll', function() {
// on scroll, if the scroll value equal or more than a certain number, fade the
// corresponding frame in, then increase index by one.
if (win.scrollTop() >= index * steps) {
jQ(frames[index]).animate({'opacity': 1}, 50);
index++;
} else {
// else if it's less, hide the relative frame then decrease the index by one
// thus it will work whether the user scrolls up or down
jQ(frames[index]).animate({'opacity': 0}, 50);
index--;
}
});
Update:
Considering another scenario, where we have the frames inside a scroll-able div, then we wrap the .frame images within another div .inner.
jsFiddle 2
var jQ = $.noConflict(),
cont = jQ('#frames-container'),
inner = jQ('#inner-div'),
frames = jQ('.frame'),
frameHeight = jQ('#frame1').height(),
frameWidth = jQ('#frame1').width() + 20, // we add 20px because of the horizontal scroll
index = 0;
// set the height of the outer container div to be same as 1 frame height
// and the inner div height to be the sum of all frames height, also we
// add some pixels just for safety, 20px here
cont.css({'height': frameHeight, 'width': frameWidth});
inner.css({'height': frameHeight * frames.length + 20});
cont.on('scroll', function() {
var space = index * frameHeight;
if (cont.scrollTop() >= space) {
jQ(frames[index]).animate({'opacity': 1}, 0);
index++;
} else {
jQ(frames[index]).animate({'opacity': 0}, 0);
index--;
}
});
** Please Note that in both cases all frames must have same height.

Finding position of element within scrollable div

I have these "pages" aka div's inside a scrollable container. On command, I am trying to find out what part of the div in question, is touching the top of .pageContent.
So for example, right when the page loads, no part of #page_1 is touching the top of pageContent, but as I scroll down. #page_1 hits the top of .pageContent and I now want to figure out where that is.
I know I can get the position of .pageContent using $("#pageContent").scrollTop() but these page's could be different sizes and I am not sure how to go about figuring it out.
Could anyone put me in the right direction?
jsfiddle
HTML
<div id="pageContent">
<div id="page_1" class="content"></div>
<div id="page_2" class="content"></div>
<div id="page_3" class="content"></div>
</div>
CSS
#pageContent {
overflow: auto;
width:500px;
height:300px;
padding:10px;
border:1px solid black;
background-color:grey;
}
.content {
height:400px;
width:300px;
margin:0 auto;
background-color:red;
margin-bottom:10px;
}
You can use the jQuery .position() function to compute where each page is in relation to the top of the container. See this Fiddle.
For example, for #page_1,
var page1 = $('#page_1');
$('#pageContent').scroll(function() {
// page1.position().top gives the position of page_1 relative to the
// top of #pageContent
});
ScrollTop can be used, be I wouldn't recommend it.
Attach a scroll event to your main div and listener for all the objects inside:
$('#pageContent').scroll(function(){
var pages = $("#pageContent > .content");
for (var i = 0; i < pages.length; i++)
{
if ($(pages[i]).position().top < 0 && ( $(pages[i]).position().top + $(pages[i]).outerHeight() ) > 0)
{
var outerHeight = $(pages[i]).outerHeight();
var pixels = (outerHeight - (outerHeight + $(pages[i]).position().top));
console.log("These pixels are in view between: " + pixels + " and " + outerHeight );
}
}
})
Every time the div scroll a loop is performed checking the position of all elements. If the elements scroll out of view a the top the if is triggered, calculating the remaining visible pixels of the page currently visible.
This uses jQuery's: position() and outerHeight() and JavaScript's native offsetTop.
http://jsfiddle.net/q5aaLo9L/4/
I tried something like this
$(document).ready(function () {
var divs = $('.content').map(function (i, el) {
return $(el).offset().top - $(el).parent().offset().top;
});
$('#pageContent').scroll(function () {
var index = findIndex($(this).scrollTop(), divs) - 1;
if (index > -1) {
console.log($(this).children().eq(index).attr('id'));
} else {
console.log('outside');
}
});
});
function findIndex(pos, divs) {
return (divs.filter(function (el, et) {
return et <= pos
}).length);
}
It's not super clean code because I had to do it quickly.
DEMO
I hope this helps
I mocked this up, it uses JQuery's each() function to iterate through the pages and return the information of the page that has breached the top of the box.
I wasn't sure from your question exactly what you wanted returned, so I got it to return either the percentage of the page that has cleared the top border, the position (as negative value of pixels) of the top of the "page " in relation to the content container, and also just the ID of that div.
var getCurrentPage = function(){
var page;
var position;
var percentageRead;
$('.content').each(function(){
if($(this).position().top <= 0){
page = $(this);
position = $(this).position().top;
}
});
percentageRead = ((position *-1)/ $(page).height()* 100);
console.log(page.attr('id'));
console.log(position);
console.log(percentageRead + '%');
}
$('#pageContent').on('scroll', getCurrentPage);
You could fire this on any event but I used scroll to build it.

show div as popoup when clicking on image [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have an image.
I want to show different divs as popup when user clicks on particular area of the image.
I want to do it using jquery & html.
Can any one help me with this.
Here is an example of sample solution: http://jsfiddle.net/htEvT/2/
JavaScript
$('#rabbit').click(function (e) {
var offset = $(this).offset(),
left = e.pageX - offset.left,
top = e.pageY - offset.top;
if (top > $(this).height() / 2) {
alertDiv('You\'ve cliked under the middle.', 'alert-white');
} else {
alertDiv('You\'ve cliked above the middle.', 'alert-gray');
}
});
function alertDiv(text, cssClass) {
var alrt = $('<div class="alert ' + cssClass + '">' + text + '</div>');
$(document.body).append(alrt);
alrt.click(function () {
alrt.remove();
});
}
​
CSS
.alert {
position: absolute;
left: 30px;
top: 30px;
width: 300px;
height: 200px;
border: 1px solid black;
}
.alert-white {
background: white;
}
.alert-gray {
background: #ccc;
}
​
HTML
<img src="http://www.clermontanimal.net/images/lop_rabbit_easter.jpg" id="rabbit" alt="" />​
If there are any issues with my solution please let me know. :)
Use Image Map on image and attach fancy box on different sections of image. Since, you have not posted code so I can't provide coding solution for the same.
Something like below should give you an Idea how to do this:
$("img").click(function() {
$("body").append("<div class='newdiv'></div>")
})
.newdiv{width:100px; height:300px;border:1px solid red;}
My favorite is Fancybox.
I'm yet to see something it cannot do. Great documentation and widely used so if you need help there is a high chance somebody else has asked the same question, and can be resolved with a simple google.
Create a DIV named "imgbox" on the HTML page on which your thumbnail images will be shown. The DIV and the CSS element ID associated with the DIV is shown below
<div id="imgbox"></div>
the css
#imgbox
{
vertical-align : middle;
position : absolute;
border: 1px solid #999;
background : #FFFFFF;
filter: Alpha(Opacity=100);
visibility : hidden;
height : 200px;
width : 200px;
z-index : 50;
overflow : hidden;
text-align : center;
}
Here is the JavaScript code to show the popup image:
Get the left and top positions of the thumbnail image:
function getElementLeft(elm)
{
var x = 0;
//set x to elm’s offsetLeft
x = elm.offsetLeft;
//set elm to its offsetParent
elm = elm.offsetParent;
//use while loop to check if elm is null
// if not then add current elm’s offsetLeft to x
//offsetTop to y and set elm to its offsetParent
while(elm != null)
{
x = parseInt(x) + parseInt(elm.offsetLeft);
elm = elm.offsetParent;
}
return x;
}
function getElementTop(elm)
{
var y = 0;
//set x to elm’s offsetLeft
y = elm.offsetTop;
//set elm to its offsetParent
elm = elm.offsetParent;
//use while loop to check if elm is null
// if not then add current elm’s offsetLeft to x
//offsetTop to y and set elm to its offsetParent
while(elm != null)
{
y = parseInt(y) + parseInt(elm.offsetTop);
elm = elm.offsetParent;
}
return y;
}
Get the thumbnail image source, make the DIV visible, increase the height and width to the required size, and attach the image to the DIV.
function Large(obj)
{
var imgbox=document.getElementById("imgbox");
imgbox.style.visibility='visible';
var img = document.createElement("img");
img.src=obj.src;
img.style.width='200px';
img.style.height='200px';
if(img.addEventListener){
img.addEventListener('mouseout',Out,false);
} else {
img.attachEvent('onmouseout',Out);
}
imgbox.innerHTML='';
imgbox.appendChild(img);
imgbox.style.left=(getElementLeft(obj)-50) +'px';
imgbox.style.top=(getElementTop(obj)-50) + 'px';
}
Hide the DIV at mouse out.
function Out()
{
document.getElementById("imgbox").style.visibility='hidden';
}
Add a OnMouseOver client-side event call for the thumbnail images to show the popup image on mouse-over.
<img id='img1' src='images/Sample.jpg' onmouseover="Large(this)" />
If the area is square, you can place a transparent element over the desired area, and give it a simple onClick event.
Use SimpleModal
You can use the plugin SimpleModal to achieve what you wanna do.
SimpleModal is a lightweight jQuery Plugin which provides a powerful interface for modal dialog development. Think of it as a modal dialog framework. SimpleModal gives you the flexibility to build whatever you can envision, while shielding you from related cross-browser issues inherent with UI development.
Using that, you can either call an already existing div or create a modal on the fly.
Calling an existing div:
$("#element-id").modal();
Making a modal on the fly:
$.modal("<div><h1>SimpleModal</h1></div>");
Giving options:
$("#element-id").modal({options});
$.modal("<div><h1>SimpleModal</h1></div>", {options});
Demos:
More demos here: http://www.ericmmartin.com/projects/simplemodal-demos/

Categories

Resources