I'm trying to change the z-index on the clicked item on vanilla JS.
When a click event happens, the clicked item should come front. There are only two divs atm, but there will be more.
I'm storing the last clicked item, so that if new click event happens the last clicked item have less z-index. But it doesn't seem to work.(both of items are position relative)
Any help would be appreciated.
<div class="post" data-name="post" draggable="true">1</div>
<div class="post" data-name="post" draggable="true">2</div>
const a = new A()
memoSection.addEventListener('click', ({target})=>{
switch(target.dataset.name){
case "post":
let clickedItem ="";
a.bringFront(clickedItem)
break;
})
class A{
constructor(){
this.selected = null
}
bringFront(clickedItem){
this.selected = clickedItem; //store the previously clicked element
if(!clickedItem.style.zIndex == 10 || !clickedItem.style.zIndex){
this.selected.zIndex = 0
clickedItem.style.zIndex = 10
} else {
this.selected.zIndex = 10
clickedItem.style.zIndex = 0 }
}
}
I don't understand what your code was trying to do, but here is example how to get desired effect:
document.querySelectorAll('.post').forEach(item => {
//get all elements with class .post
item.addEventListener('click', event => {
// add Event Listener to each
document.querySelectorAll('.post').forEach(el => {
el.style.zIndex = "0";
})
// when clicked fetch all again and set all back to 0
item.style.zIndex = "10";
//set clicked only to 10
console.clear()
console.log(item.innerHTML);
})
})
.post:first-of-type {
position: absolute;
background-color: blue;
left: 100px;
top: 50px;
width: 150px;
height: 150px;
z-index: 0;
}
.post {
position: absolute;
background-color: red;
left: 25px;
top: 50px;
width: 150px;
height: 150px;
z-index: 0;
}
<div class="post" data-name="post" draggable="true">1</div>
<div class="post" data-name="post" draggable="true">2</div>
I am using popup.js to display content inside a popup. However, if I am executing the basic example, this is what I am getting:
What you see here is the popup with some uninteresting content, but you can also see that <div class="popup_cont" ..> has been added several times to the DOM tree. The result is that I have to click (here) 7 times to get rid of the popup. Each click removes one of those overlays..
I have no idea why this is happening. This is how I embed the popup:
<div id="btn-help" class="toy-button">
<span lang="en">
HELP
</span>
</div>
And this is how it gets invoked:
/**
* Callback to display help window.
* #private
* #memberOf module:cpu-controlls_controller
*/
_onHelpButtonClicked = function() {
debug('cpu-controlls.controller _onHelpButtonClicked()');
var options = { content : "hallo.html" };
$('.default_popup').popup(options);
};
Where the hallo.html is just a .html file with a lot of "Hello World!" messages.
Any idea how I can solve this?
It seems like you initialize the popup plugin every time the user clicks on the button, so the first time it will work okay, but with every next click you will have more and more popups to close.
Put the initialization in the document.ready() function, and out of the click handler.
There are two different ways to popup the window (in any case I use always full url path):
/*-------------------------------
POPUP.JS
Simple Popup plugin for jQuery
#author Todd Francis
#version 2.2.3
-------------------------------*/
;(function(b,t){b.fn.popup=function(h){var q=this.selector,m=new b.Popup(h);b(document).on("click.popup",q,function(n){var k=h&&h.content?h.content:b(this).attr("href");n.preventDefault();m.open(k,void 0,this)});return this.each(function(){b(this).data("popup",m)})};b.Popup=function(h){function q(a){var d;b.each(a,function(a,c){if(c)return d=c,!1});return d}function m(a){return"function"===typeof a?"function":a instanceof b?"jQuery":"#"===a.substr(0,1)||"."===a.substr(0,1)?"inline":-1!==b.inArray(a.substr(a.length-
3),u)?"image":"http"===a.substr(0,4)?"external":"ajax"}function n(c){r&&r.fadeOut("fast",function(){b(this).remove()});var d=!0;void 0===f&&(d=!1,f=b('<div class="'+a.o.containerClass+'">'),p=b(a.o.markup).appendTo(f),b(a.o.closeContent).one("click",function(){a.close()}).appendTo(f),b(t).resize(a.center),f.appendTo(b("body")).css("opacity",0));var e=b("."+a.o.contentClass,f);a.width?e.css("width",a.width,10):e.css("width","");a.height?e.css("height",a.height,10):e.css("height","");p.hasClass(a.o.contentClass)?
p.html(c):p.find("."+a.o.contentClass).html(c);d?a.o.replaced.call(a,f,g):a.o.show.call(a,f,g)}function k(a,d){var b=(new RegExp("[?&]"+a+"=([^&]*)")).exec(d);return b&&decodeURIComponent(b[1].replace(/\+/g," "))}var a=this,u=["png","jpg","gif"],l,s,g,f,r,p;a.ele=void 0;a.o=b.extend(!0,{},{backClass:"popup_back",backOpacity:.7,containerClass:"popup_cont",closeContent:'<div class="popup_close">×</div>',markup:'<div class="popup"><div class="popup_content"/></div>',contentClass:"popup_content",
preloaderContent:'<p class="preloader">Loading</p>',activeClass:"popup_active",hideFlash:!1,speed:200,popupPlaceholderClass:"popup_placeholder",keepInlineChanges:!0,modal:!1,content:null,type:"auto",width:null,height:null,typeParam:"pt",widthParam:"pw",heightParam:"ph",beforeOpen:function(a){},afterOpen:function(){},beforeClose:function(){},afterClose:function(){},error:function(){},show:function(a,b){var e=this;e.center();a.animate({opacity:1},e.o.speed,function(){e.o.afterOpen.call(e)})},replaced:function(a,
b){this.center().o.afterOpen.call(this)},hide:function(a,b){void 0!==a&&a.animate({opacity:0},this.o.speed)},types:{inline:function(c,d){var e=b(c);e.addClass(a.o.popupPlaceholderClass);a.o.keepInlineChanges||(s=e.html());d.call(this,e.children())},image:function(c,d){var e=this;b("<img />").one("load",function(){var a=this;setTimeout(function(){d.call(e,a)},0)}).one("error",function(){a.o.error.call(a,c,"image")}).attr("src",c).each(function(){this.complete&&b(this).trigger("load")})},external:function(c,
d){var e=b("<iframe />").attr({src:c,frameborder:0,width:a.width,height:a.height});d.call(this,e)},html:function(a,b){b.call(this,a)},jQuery:function(a,b){b.call(this,a.html())},"function":function(b,d){d.call(this,b.call(a))},ajax:function(c,d){b.ajax({url:c,success:function(a){d.call(this,a)},error:function(b){a.o.error.call(a,c,"ajax")}})}}},h);a.open=function(c,d,e){c=void 0===c||"#"===c?a.o.content:c;if(null===c)return a.o.error.call(a,c,l),!1;void 0!==e&&(a.ele&&a.o.activeClass&&b(a.ele).removeClass(a.o.activeClass),
a.ele=e,a.ele&&a.o.activeClass&&b(a.ele).addClass(a.o.activeClass));if(void 0===g){g=b('<div class="'+a.o.backClass+'"/>').appendTo(b("body")).css("opacity",0).animate({opacity:a.o.backOpacity},a.o.speed);if(!a.o.modal)g.one("click.popup",function(){a.close()});a.o.hideFlash&&b("object, embed").css("visibility","hidden");a.o.preloaderContent&&(r=b(a.o.preloaderContent).appendTo(b("body")))}d=q([d,a.o.type]);l=d="auto"===d?m(c):d;a.width=a.o.width?a.o.width:null;a.height=a.o.height?a.o.height:null;
if(-1===b.inArray(d,["inline","jQuery","function"])){e=k(a.o.typeParam,c);var f=k(a.o.widthParam,c),h=k(a.o.heightParam,c);d=null!==e?e:d;a.width=null!==f?f:a.width;a.height=null!==h?h:a.height}a.o.beforeOpen.call(a,d);a.o.types[d]?a.o.types[d].call(a,c,n):a.o.types.ajax.call(a,c,n)};a.close=function(){a.o.beforeClose.call(a);"inline"===l&&a.o.keepInlineChanges&&(s=b("."+a.o.contentClass).html());void 0!==g&&g.animate({opacity:0},a.o.speed,function(){a.cleanUp()});a.o.hide.call(a,f,g);return a};a.cleanUp=
function(){g.add(f).remove();f=g=void 0;b(t).unbind("resize",a.center);a.o.hideFlash&&b("object, embed").css("visibility","visible");a.ele&&a.o.activeClass&&b(a.ele).removeClass(a.o.activeClass);var c=b("."+a.o.popupPlaceholderClass);"inline"==l&&c.length&&c.html(s).removeClass(a.o.popupPlaceholderClass);l=null;a.o.afterClose.call(a);return a};a.center=function(){f.css(a.getCenter());g.css({height:document.documentElement.clientHeight});return a};a.getCenter=function(){var a=f.children().outerWidth(!0),
b=f.children().outerHeight(!0);return{top:.5*document.documentElement.clientHeight-.5*b,left:.5*document.documentElement.clientWidth-.5*a}}}})(jQuery,window);
$(function () {
// first method
$('.default_popup').popup();
// second method
$('.default_popup1').click(function(e) {
e.preventDefault();
var popup = new $.Popup();
popup.open('http://stackoverflow.com/');
});
});
/*-------------------------------
POPUP.CSS
-------------------------------*/
.popup_back {
height: 100%;
left: 0;
position: fixed;
top: 0;
width: 100%;
z-index: 100;
}
.popup_cont {
position: fixed;
z-index: 102;
}
.preloader {
z-index: 101;
}
/*---------------------
EDIT BELOW
*/
.popup_close {
color: #888;
cursor: pointer;
position: absolute;
padding: 5px;
right: 5px;
top: 0;
}
.popup_close:hover {
color: #111;
}
.popup_back {
cursor: pointer;
background-color: #222;
}
div.popup {
background: #fff;
padding: 25px;
box-shadow: 0 3px 10px #222;
}
.preloader {
left: 50%;
margin: -10px 0 0 -25px;
position: fixed;
top: 50%;
}
<script src="//code.jquery.com/jquery-1.11.3.js"></script>
<div id="btn-help" class="toy-button">
<span lang="en">
HELP1
</span>
</div>
<div id="btn-help1" class="toy-button">
<span lang="en">
HELP2
</span>
</div>
I'm not great with JS so been using trial and error to try and figure out how to get 2 divs to swap z-index on the click of a trigger (button).
I currently have 2 drawers that technically are on top of each other and slide out from the right. On click of 'Buy' the #QuickShopDrawer should open and on click of 'Cart' or 'Add to Cart' the #CartDrawer should open.
Link to my test store.
My code so far is making the open with the #CartDrawer on top with a higher z-index.
JS:
Drawer.prototype.init = function () {
$(this.config.open).on('click', $.proxy(this.open, this));
$('.js-drawer-open-right-two').click(function(){
$(this).data('clicked', true);
});
if($('.js-drawer-open-right-two').data('clicked')) {
//clicked element, do-some-stuff
$('#QuickShopDrawer').css('z-index', '999');
} else {
//run function 2
$('#CartDrawer').css('z-index', '999');
}
this.$drawer.find(this.config.close).on('click', $.proxy(this.close, this));
};
I've tried this which is more of what I want but it's only firing once?
$('.js-drawer-open-right-two').click(function() {
var i = $(this).index();
$('.drawer--right').hide();
$('.drawer--right-two' + (i+1)).show();
});
Any help would be greatly appreciated!
You need to swap the z-index of the elements on button click. Also, you can disable the button on click so that user cannot click it continiously.
Demo
$(document).ready(function() {
$('#buy').on('click', function(e) {
var myZindex = $('#QuickShopDrawer').css('z-index');
$('#QuickShopDrawer').css('z-index', $('#CartDrawer').css('z-index'));
$('#CartDrawer').css('z-index', myZindex);
$(this).prop('disabled', true).siblings('button').prop('disabled', false);
});
$('#addToCart').on('click', function(e) {
var myZindex = $('#CartDrawer').css('z-index');
$('#CartDrawer').css('z-index', $('#QuickShopDrawer').css('z-index'));
$('#QuickShopDrawer').css('z-index', myZindex);
$(this).prop('disabled', true).siblings('button').prop('disabled', false);
});
});
button {
position: absolute;
top: 150px;
left: 0;
clear: both;
}
#addToCart {
margin-left: 50px;
}
.red {
position: absolute;
width: 100px;
height: 100px;
background-color: red;
left: 20px;
top: 20px;
z-index: 1;
}
.green {
position: absolute;
width: 100px;
height: 100px;
background-color: green;
z-index: 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div>
<div id="QuickShopDrawer" class="red">fdsafdsafdsa</div>
<div id="CartDrawer" class="green">fdsafdsafdsa</div>
</div>
<button id="buy">Buy</button>
<button id="addToCart">Add To Cart</button>
Am currently working with the Soundcloud API to pull images and track links for songs. Am currently showing track info through a modal window upon clicking the album image. However, for the songs on the bottom of the screen, the modal window only appears at the top of the screen, requiring a user to scroll up to see the track info. Probably has something to do with the css positioning but removing position:absolute only puts the modal window at the bottom of all the album images, requiring a scroll down. How can I make it so that a user's click on an image will open and start the modal window right where they currently are, without scrolling? Javascript / jquery /css answers all welcomed.
My CSS:
#modal {
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.2);
position: absolute;
top: 0;
left: 0;
}
#trackinfo {
width:380px;
height: 180px;
padding: 20px;
margin-right: auto;
margin-left: auto;
margin-top: 100px;
box-shadow: 10px 10px 5px;
border-radius: 15px;
text-align: center;
background: #c4e5c1;
font-family: Rockwell, "Courier Bold", Courier, Georgia, Times, "Times New Roman", serif;
}
.hidden {
display:none;
}
My Javascript for show and hide modal:
function doSearch() {
var searchTerm = document.getElementById('search').value;
// Search soundcloud for artists
SC.get('/tracks', { q: searchTerm}, function(tracks) {
for(track in tracks) {
var img = document.createElement('img');
img.setAttribute("src", (tracks[track]["artwork_url"]));
var title = tracks[track].title.replace("'", "\\\'").replace("\"", "\\\"");
linky = document.createElement('a');
linky.setAttribute("href", (tracks[track].permalink_url));
console.log(linky);
img.setAttribute("onclick", "showTrackInfo('" + title + "\\n"+ tracks[track].uri + " " + "\\n\\n(click to close) " + "')");
console.log(img);
if (tracks[track]["artwork_url"] == null) {
console.log(""); }
else {
var Catalog = document.getElementById('catalog');
Catalog.appendChild(img);
$('div#catalog').append('<img src="http://i.imgur.com/rGdvfl7.png">');
}
}
});
};
function showTrackInfo(track) {
var trackInfoElement = document.getElementById("trackinfo");
trackInfoElement.appendChild(document.createTextNode(track));
var modal = document.getElementById("modal");
modal.setAttribute("class", "");
}
function hidemodal() {
var trackInfoElement = document.getElementById("trackinfo");
trackInfoElement.childNodes;
while ( trackInfoElement.firstChild ) trackInfoElement.removeChild( trackInfoElement.firstChild );
var modal = document.getElementById("modal");
modal.setAttribute("class", "hidden");
}
The functions all work well, I just need to know how to position the modal box upon click so that the user doesn't need to scroll to see the trackinfo. Any help much appreciated.
Try position: fixed; on the dialog box, should make it fill the page no matter where they are on it
I have been looking all day for a way to make a contact form similar to the one on this site: http://45royale.com/
If you click on the contact button a black background fades in and the from drops down using an ease function. I have been picking through the code trying to see what to do but I am stuck and I have also been looking and other javascript pop ups but so far it seems they only use php for the form however this one calls a html.
Any suggestions?
Here is something like the form in the example: http://jsfiddle.net/ep39v/3/.
And the source:
HTML
<div class="form"></div>
<button id="showFormBtn">Show form</button>
JavaScript
var form = $('.form');
$('#showFormBtn').click(function () {
fadeBackground(showForm);
});
(function () {
form.css({
top: -form.height(),
left: ($(document.body).width() - form.width()) / 2
});
}());
function fadeBackground(callback) {
var background = $('<div class="background"></div>');
$(document.body).append(background);
background.fadeTo(300, 0.5, function () {
if (typeof callback === 'function') {
callback();
}
});
}
function showForm() {
var form = $('.form');
form.animate({ top: 10 }, 1500, 'easeOutElastic');
}
CSS
.form {
width: 30%;
height: 40%;
background: black;
position: absolute;
}
body {
height: 100%;
}
.background {
height: 100%;
width: 100%;
position: absolute;
top: 0px;
left: 0px;
background: black;
opacity: 0;
}
May be you need to change only the easing.