Javascript Show/Hide text - javascript
I'm trying to have a list in which when a user clicks, an image shows up along with a text under it. Let's say for List 1, I want it to say "Price: $1" when the link is clicked. And then for List 2, "Price: $2" under the image when the link is clicked. The same functions as the image show/hide ideally. Then when clicked away, hides the elements. I'm fairly new to JS but here's what I've gathered so far:
$(function () {
$(".imgPreview").hide();
$(".unstyled li a").click(function () {
$(".imgPreview").show().find("img").attr("src", $(this).attr("href"));
return false;
});
$("body").click(function () {
$(".imgPreview").hide();
});
});
* {font-family: 'Segoe UI'; margin: 0; padding: 0; list-style: none;}
body {margin: 10px;}
li {margin: 25px;}
.unstyled, .imgPreview, .showPrice {float: left; width: 50%;}
.unstyled, .imgPreview img {max-width: 100%;}
p {margin: 5px;}
.recycle-button {
padding: 6px 6px;
background-color: rgb(53, 189, 208);
border-radius: 5px;
color: white;
margin-bottom: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div style="margin-bottom: 35px;">
<h3>LIST</h3> </div>
<ul class="unstyled">
<li>List 1</li>
<li>List 2</li>
<li>List 3</li>
<li>List 4</li>
<li>List 5</li>
<li>List 6</li>
</ul>
<div class="imgPreview">
<img src="" alt="" width="350" height="150"/>
</div>
My goal is to have something like this.
Edit:
So far, I've tried adding the attribute data-price to the element <a to hold the price data:
<li>List 1</li>
and have the script do the same function with the imgPreview:
$(".imgPreview").show().find("p").attr($(this).attr("data-price"));
I'm fiddling with this and the error I get is "Script error." Surely, you can see the limited knowledge I have with JS.
May be you want something like this...
$(function () {
$(".imgPreview").hide();
$(".unstyled li a").click(function (event) {
var listItem = event.target.parentElement;
var image = $(".imgPreview");
image.show();
image.find("img").attr("src", $(this).attr("href"));
$(image.find("span"))[0].innerHTML="Price = $"+ ($( "li" ).index( listItem ) + 1);
return false;
});
$("body").click(function () {
$(".imgPreview").hide();
});
});
* {font-family: 'Segoe UI'; margin: 0; padding: 0; list-style: none;}
body {margin: 10px;}
li {margin: 25px;}
.unstyled, .imgPreview, .showPrice {float: left; width: 50%;}
.unstyled, .imgPreview img {max-width: 100%;}
p {margin: 5px;}
.recycle-button {
padding: 6px 6px;
background-color: rgb(53, 189, 208);
border-radius: 5px;
color: white;
margin-bottom: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div style="margin-bottom: 35px;">
<h3>LIST</h3> </div>
<ul class="unstyled">
<li>List 1</li>
<li>List 2</li>
<li>List 3</li>
<li>List 4</li>
<li>List 5</li>
<li>List 6</li>
</ul>
<div class="imgPreview">
<img src="" alt="" width="350" height="150"/>
<span id="priceView"></span>
</div>
Related
Unable to remove class after using toggle class with jQuery
I have three navigations in one page and I'm trying to show the active links for each nav. For some reason the third nav isn't working correctly. For example, if you click on "chapter 2" or "chapter 3" or "chapter 4", "chapter 1" stays active. I don't know if it's because "Chapter 1" and "sublink4" from the middle nav have the same url. I tried removing the active class of the third nav, but it's not working. Unfortunately the snipping isn't working as it is on my computer. I only used target="_blank" on the snippet, not only my local machine since you can't click on links on the snippet without restarting the snippet.Thanks $(window).on('load', function () { $('body').setActiveMenuItem(); $('body').setActiveMenuItem2(); $('body').setActiveMenuItem3(); }); $(document).ready(function () { //first nav $.fn.setActiveMenuItem2 = function () { $.each($('.nav1').find('li'), function () { $(this).toggleClass('active', window.location.pathname.indexOf($(this).find('a').attr('href')) > -1); }); } //middle nav $.fn.setActiveMenuItem3 = function () { $.each($('.nav3').find('li'), function () { $(this).toggleClass('active3', window.location.pathname.indexOf($(this).find('a').attr('href')) > -1); }); } //third nav $.fn.setActiveMenuItem = function () { $.each($('.nav2').find('li'), function () { $(this).removeClass('active2'); $(this).toggleClass('active2', window.location.pathname.indexOf($(this).find('a').attr('href')) > -1); }); } }); li.active { background-color: red; } li.active2 { background-color: blue; } li.active { background-color: yellow; } .nav1 ul, .nav3 ul { display: flex; justify-content: space-between; } nav { margin-bottom: 50px; } .wrapper { width: 400px; margin: auto; } li { list-style: none; background-color: aliceblue; padding: 10px; } li a { padding: 10px; } li a:hover { color: red; background: black; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="wrapper"> <nav class="nav1"> <ul> <li> Link 1 </li> <li><a href="/link-2" target="_blank" >Link 2</a> </li> <li>Link 3 </li> <li>Link 4 </li> </ul> </nav> <nav class="nav3"> <ul> <li>Subink 1</li> <li>Subink 2</li> <li>Subink 3</li> </ul> </nav> <nav class="nav2"> <ul> <li>Chapter 1</li> <li>Chapter 2</li> <li>Chapter 3</li> </ul> </nav> </div>
-> replace $ to j Query ->Either replace a latest jquery
Use preventDefault to let default event handler to open new link. window.open() will let you open links in new tabs. Note: This code won't work in sand-boxes. Let me know if I'm missing something? var links = document.querySelectorAll('a'); links.forEach((node) => { node.addEventListener("click", (evt) => { evt.stopPropagation(); evt.preventDefault(); evt.target.classList.add('active'); window.open(evt.target.href); }); }); li.active { background-color: red; } li.active2 { background-color: blue; } li.active { background-color: yellow; } .nav1 ul, .nav3 ul { display: flex; justify-content: space-between; } nav { margin-bottom: 50px; } .wrapper { width: 400px; margin: auto; } li { list-style: none; background-color: aliceblue; padding: 10px; } li a { padding: 10px; } li a:hover { color: red; background: black; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="wrapper"> <nav class="nav1"> <ul> <li> Link 1 </li> <li>Link 2 </li> <li>Link 3 </li> <li>Link 4 </li> </ul> </nav> <nav class="nav3"> <ul> <li>Subink 1</li> <li>Subink 2</li> <li>Subink 3</li> </ul> </nav> <nav class="nav2"> <ul> <li>Chapter 1</li> <li>Chapter 2</li> <li>Chapter 3</li> </ul> </nav> </div>
ondrop event - create new element
Im using sortable feature of jquery. please check the image, If i drag an item from Base Data and drop it in Filters, i need a text box to be created on Texfields column. i dont want to pre populate all the Filters and Textfields. so if i can drag and drop a item from base data that i require to Filters. A text box should be create for each drop.. help please!!! my code HTML <div class="col-md-3"> <h4>Base Data</h4> <ol class="simple_with_no_drop vertical"> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> </ol> </div> <div class="col-md-3"> <h4>Filters</h4> <ol class="simple_with_no_drag vertical" style="border: 1px solid #444;"> <br> </ol> </div> <div class="col-md-3"> <h4>Textfields</h4> <ol class="" style="border: 1px solid #444;"><br> </ol> </div> <div class="col-md-3"> <h4>Hierarchy</h4> <ol class="simple_with_drop vertical"> <li>Item 3</li> <li>Item 3</li> <li>Item 3</li> <li>Item 3</li> </ol> </div> CSS body.dragging, body.dragging * { cursor: move !important; } .dragged { position: absolute; top: 0; opacity: 0.5; z-index: 2000; } ol.vertical { margin: 0 0 9px 0; min-height: 10px; } ol.vertical li { display: block; margin: 5px; padding: 5px; border: 1px solid #cccccc; color: #0088cc; background: #eeeeee; } ol.vertical li.placeholder { position: relative; margin: 0; padding: 0; border: none; } JS/Jquery $(function () { $("ol.simple_with_drop").sortable({ group: 'no-drop', onDragStart: function ($item, container, _super) { // Duplicate items of the no drop area if (!container.options.drop) $item.clone().insertAfter($item); _super($item, container); } }); $("ol.simple_with_no_drop").sortable({ group: 'no-drop', drop: false }); $("ol.simple_with_no_drag").sortable({ group: 'no-drop', drag: false }); });
Please check below mentioned solution. It will help you. !function(t,e,i,o){function s(t,e){var i=Math.max(0,t[0]-e[0],e[0]-t[1]),o=Math.max(0,t[2]-e[1],e[1]-t[3]);return i+o}function n(e,i,o,s){var n=e.length,r=s?"offset":"position";for(o=o||0;n--;){var a=e[n].el?e[n].el:t(e[n]),h=a[r]();h.left+=parseInt(a.css("margin-left"),10),h.top+=parseInt(a.css("margin-top"),10),i[n]=[h.left-o,h.left+a.outerWidth()+o,h.top-o,h.top+a.outerHeight()+o]}}function r(t,e){var i=e.offset();return{left:t.left-i.left,top:t.top-i.top}}function a(t,e,i){e=[e.left,e.top],i=i&&[i.left,i.top];for(var o,n=t.length,r=[];n--;)o=t[n],r[n]=[n,s(o,e),i&&s(o,i)];return r=r.sort(function(t,e){return e[1]-t[1]||e[2]-t[2]||e[0]-t[0]})}function h(e){this.options=t.extend({},u,e),this.containers=[],this.options.rootGroup||(this.scrollProxy=t.proxy(this.scroll,this),this.dragProxy=t.proxy(this.drag,this),this.dropProxy=t.proxy(this.drop,this),this.placeholder=t(this.options.placeholder),e.isValidTarget||(this.options.isValidTarget=o))}function l(e,i){this.el=e,this.options=t.extend({},c,i),this.group=h.get(this.options),this.rootGroup=this.options.rootGroup||this.group,this.handle=this.rootGroup.options.handle||this.rootGroup.options.itemSelector;var o=this.rootGroup.options.itemPath;this.target=o?this.el.find(o):this.el,this.target.on(g.start,this.handle,t.proxy(this.dragInit,this)),this.options.drop&&this.group.containers.push(this)}var c={drag:!0,drop:!0,exclude:"",nested:!0,vertical:!0},u={afterMove:function(t,e,i){},containerPath:"",containerSelector:"ol, ul",distance:0,delay:0,handle:"",itemPath:"",itemSelector:"li",bodyClass:"dragging",draggedClass:"dragged",isValidTarget:function(t,e){return!0},onCancel:function(t,e,i,o){},onDrag:function(t,e,i,o){t.css(e)},onDragStart:function(e,i,o,s){e.css({height:e.outerHeight(),width:e.outerWidth()}),e.addClass(i.group.options.draggedClass),t("body").addClass(i.group.options.bodyClass)},onDrop:function(e,i,o,s){e.removeClass(i.group.options.draggedClass).removeAttr("style"),t("body").removeClass(i.group.options.bodyClass)},onMousedown:function(t,e,i){return i.target.nodeName.match(/^(input|select|textarea)$/i)?void 0:(i.preventDefault(),!0)},placeholderClass:"placeholder",placeholder:'<li class="placeholder"></li>',pullPlaceholder:!0,serialize:function(e,i,o){var s=t.extend({},e.data());return o?[i]:(i[0]&&(s.children=i),delete s.subContainers,delete s.sortable,s)},tolerance:0},p={},f=0,d={left:0,top:0,bottom:0,right:0},g={start:"touchstart.sortable mousedown.sortable",drop:"touchend.sortable touchcancel.sortable mouseup.sortable",drag:"touchmove.sortable mousemove.sortable",scroll:"scroll.sortable"},m="subContainers";h.get=function(t){return p[t.group]||(t.group===o&&(t.group=f++),p[t.group]=new h(t)),p[t.group]},h.prototype={dragInit:function(e,i){this.$document=t(i.el[0].ownerDocument);var o=t(e.target).closest(this.options.itemSelector);if(o.length){if(this.item=o,this.itemContainer=i,this.item.is(this.options.exclude)||!this.options.onMousedown(this.item,u.onMousedown,e))return;this.setPointer(e),this.toggleListeners("on"),this.setupDelayTimer(),this.dragInitDone=!0}},drag:function(t){if(!this.dragging){if(!this.distanceMet(t)||!this.delayMet)return;this.options.onDragStart(this.item,this.itemContainer,u.onDragStart,t),this.item.before(this.placeholder),this.dragging=!0}this.setPointer(t),this.options.onDrag(this.item,r(this.pointer,this.item.offsetParent()),u.onDrag,t);var e=this.getPointer(t),i=this.sameResultBox,s=this.options.tolerance;(!i||i.top-s>e.top||i.bottom+s<e.top||i.left-s>e.left||i.right+s<e.left)&&(this.searchValidTarget()||(this.placeholder.detach(),this.lastAppendedItem=o))},drop:function(t){this.toggleListeners("off"),this.dragInitDone=!1,this.dragging&&(this.placeholder.closest("html")[0]?this.placeholder.before(this.item).detach():this.options.onCancel(this.item,this.itemContainer,u.onCancel,t),this.options.onDrop(this.item,this.getContainer(this.item),u.onDrop,t),this.clearDimensions(),this.clearOffsetParent(),this.lastAppendedItem=this.sameResultBox=o,this.dragging=!1)},searchValidTarget:function(t,e){t||(t=this.relativePointer||this.pointer,e=this.lastRelativePointer||this.lastPointer);for(var i=a(this.getContainerDimensions(),t,e),s=i.length;s--;){var n=i[s][0],h=i[s][1];if(!h||this.options.pullPlaceholder){var l=this.containers[n];if(!l.disabled){if(!this.$getOffsetParent()){var c=l.getItemOffsetParent();t=r(t,c),e=r(e,c)}if(l.searchValidTarget(t,e))return!0}}}this.sameResultBox&&(this.sameResultBox=o)},movePlaceholder:function(t,e,i,o){var s=this.lastAppendedItem;(o||!s||s[0]!==e[0])&&(e[i](this.placeholder),this.lastAppendedItem=e,this.sameResultBox=o,this.options.afterMove(this.placeholder,t,e))},getContainerDimensions:function(){return this.containerDimensions||n(this.containers,this.containerDimensions=[],this.options.tolerance,!this.$getOffsetParent()),this.containerDimensions},getContainer:function(t){return t.closest(this.options.containerSelector).data(i)},$getOffsetParent:function(){if(this.offsetParent===o){var t=this.containers.length-1,e=this.containers[t].getItemOffsetParent();if(!this.options.rootGroup)for(;t--;)if(e[0]!=this.containers[t].getItemOffsetParent()[0]){e=!1;break}this.offsetParent=e}return this.offsetParent},setPointer:function(t){var e=this.getPointer(t);if(this.$getOffsetParent()){var i=r(e,this.$getOffsetParent());this.lastRelativePointer=this.relativePointer,this.relativePointer=i}this.lastPointer=this.pointer,this.pointer=e},distanceMet:function(t){var e=this.getPointer(t);return Math.max(Math.abs(this.pointer.left-e.left),Math.abs(this.pointer.top-e.top))>=this.options.distance},getPointer:function(t){var e=t.originalEvent||t.originalEvent.touches&&t.originalEvent.touches[0];return{left:t.pageX||e.pageX,top:t.pageY||e.pageY}},setupDelayTimer:function(){var t=this;this.delayMet=!this.options.delay,this.delayMet||(clearTimeout(this._mouseDelayTimer),this._mouseDelayTimer=setTimeout(function(){t.delayMet=!0},this.options.delay))},scroll:function(t){this.clearDimensions(),this.clearOffsetParent()},toggleListeners:function(e){var i=this,o=["drag","drop","scroll"];t.each(o,function(t,o){i.$document[e](g[o],i[o+"Proxy"])})},clearOffsetParent:function(){this.offsetParent=o},clearDimensions:function(){this.traverse(function(t){t._clearDimensions()})},traverse:function(t){t(this);for(var e=this.containers.length;e--;)this.containers[e].traverse(t)},_clearDimensions:function(){this.containerDimensions=o},_destroy:function(){p[this.options.group]=o}},l.prototype={dragInit:function(t){var e=this.rootGroup;!this.disabled&&!e.dragInitDone&&this.options.drag&&this.isValidDrag(t)&&e.dragInit(t,this)},isValidDrag:function(t){return 1==t.which||"touchstart"==t.type&&1==t.originalEvent.touches.length},searchValidTarget:function(t,e){var i=a(this.getItemDimensions(),t,e),o=i.length,s=this.rootGroup,n=!s.options.isValidTarget||s.options.isValidTarget(s.item,this);if(!o&&n)return s.movePlaceholder(this,this.target,"append"),!0;for(;o--;){var r=i[o][0],h=i[o][1];if(!h&&this.hasChildGroup(r)){var l=this.getContainerGroup(r).searchValidTarget(t,e);if(l)return!0}else if(n)return this.movePlaceholder(r,t),!0}},movePlaceholder:function(e,i){var o=t(this.items[e]),s=this.itemDimensions[e],n="after",r=o.outerWidth(),a=o.outerHeight(),h=o.offset(),l={left:h.left,right:h.left+r,top:h.top,bottom:h.top+a};if(this.options.vertical){var c=(s[2]+s[3])/2,u=i.top<=c;u?(n="before",l.bottom-=a/2):l.top+=a/2}else{var p=(s[0]+s[1])/2,f=i.left<=p;f?(n="before",l.right-=r/2):l.left+=r/2}this.hasChildGroup(e)&&(l=d),this.rootGroup.movePlaceholder(this,o,n,l)},getItemDimensions:function(){return this.itemDimensions||(this.items=this.$getChildren(this.el,"item").filter(":not(."+this.group.options.placeholderClass+", ."+this.group.options.draggedClass+")").get(),n(this.items,this.itemDimensions=[],this.options.tolerance)),this.itemDimensions},getItemOffsetParent:function(){var t,e=this.el;return t="relative"===e.css("position")||"absolute"===e.css("position")||"fixed"===e.css("position")?e:e.offsetParent()},hasChildGroup:function(t){return this.options.nested&&this.getContainerGroup(t)},getContainerGroup:function(e){var s=t.data(this.items[e],m);if(s===o){var n=this.$getChildren(this.items[e],"container");if(s=!1,n[0]){var r=t.extend({},this.options,{rootGroup:this.rootGroup,group:f++});s=n[i](r).data(i).group}t.data(this.items[e],m,s)}return s},$getChildren:function(e,i){var o=this.rootGroup.options,s=o[i+"Path"],n=o[i+"Selector"];return e=t(e),s&&(e=e.find(s)),e.children(n)},_serialize:function(e,i){var o=this,s=i?"item":"container",n=this.$getChildren(e,s).not(this.options.exclude).map(function(){return o._serialize(t(this),!i)}).get();return this.rootGroup.options.serialize(e,n,i)},traverse:function(e){t.each(this.items||[],function(i){var o=t.data(this,m);o&&o.traverse(e)}),e(this)},_clearDimensions:function(){this.itemDimensions=o},_destroy:function(){var e=this;this.target.off(g.start,this.handle),this.el.removeData(i),this.options.drop&&(this.group.containers=t.grep(this.group.containers,function(t){return t!=e})),t.each(this.items||[],function(){t.removeData(this,m)})}};var v={enable:function(){this.traverse(function(t){t.disabled=!1})},disable:function(){this.traverse(function(t){t.disabled=!0})},serialize:function(){return this._serialize(this.el,!0)},refresh:function(){this.traverse(function(t){t._clearDimensions()})},destroy:function(){this.traverse(function(t){t._destroy()})}};t.extend(l.prototype,v),t.fn[i]=function(e){var s=Array.prototype.slice.call(arguments,1);return this.map(function(){var n=t(this),r=n.data(i);return r&&v[e]?v[e].apply(r,s)||this:(r||e!==o&&"object"!=typeof e||n.data(i,new l(n,e)),this)})}}(jQuery,window,"sortable"); $(document).ready(function() { $("ol.simple_with_drop").sortable({ group: 'no-drop', drop: false, drag: false, onDrop: function($item, container, _super) { $('.selectedFilters').append('<li><input type="text" id="' + $item.data('id') + '" placeholder="' + $item.html() + '" /></li>'); $item.find('ol.dropdown-menu').sortable('enable'); _super($item, container); } }); $("ol.simple_with_no_drop").sortable({ group: 'no-drop', drop: false }); $("ol.simple_with_no_drag").sortable({ group: 'no-drop', drag: false }); }); body.dragging, body.dragging * { cursor: move !important; } .dragged { position: absolute; top: 0; opacity: 0.5; z-index: 2000; } ol.vertical { margin: 0 0 9px 0; min-height: 10px; } ol.vertical li { display: block; margin: 5px; padding: 5px; border: 1px solid #cccccc; color: #0088cc; background: #eeeeee; } ol.vertical li.placeholder { position: relative; margin: 0; padding: 0; border: none; } ol.selectedFilters { list-style: none; } <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="col-md-3"> <h4>Base Data</h4> <ol class="simple_with_no_drop vertical"> <li data-id="filter1">Base Item 1</li> <li data-id="filter2">Base Item 2</li> <li data-id="filter3">Base Item 3</li> </ol> </div> <div class="col-md-3"> <h4>Filters</h4> <ol id="filters" class="simple_with_no_drag vertical" style="border: 1px solid #444;"> <br> </ol> </div> <div class="col-md-3"> <h4>Textfields</h4> <ol class="selectedFilters" style="border: 1px solid #444;"><br> </ol> </div> <div class="col-md-3"> <h4>Hierarchy</h4> <ol class="simple_with_drop vertical"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> </ol> </div>
Javascript Toggle : Hide div on click of anywhere
I have two divs. When I click on 3 dots , then the div is appearing and on clicking the same 3 dots , same div is disappearing. But I want to hide the div, even if I click anywhere in the document. There are two circles. When I click on one circle, then a div is shown and when I click on another circle, then the opened div is closing and related div is opening but when I click anywhere on the document, then none of the div are closing. $("#discussion_declined , #discussion_pending").click(function() { var relatedDiv = $(this).closest('.panel').find('.discussion_edit_div'); relatedDiv.toggle("fast"); $('.discussion_edit_div').not(relatedDiv).hide('fast'); }); .discussion_small_round_div { width: 25px; height: 25px; border-radius: 50%; position: relative; background: #2d3446; bottom: 9px; left: 15px; float: right; } .discussion_small_round_div:after { content: '\2807'; font-size: 1.5em; color: white; position: absolute; left: 9px; top: 1px; } .discussion_edit_div { background: #FFFFFF; display: none; position: absolute; right: 35px; border: thin #ced0d1 solid; z-index: 1001; width: 150px; box-shadow: 0px 3px 3px #ccc; } ul li { padding: 5px 15px; list-style-type: none; color: #838383; } ul li:hover { background: #eeeded; cursor: pointer; } <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <div class="panel discussion_panel_div no_background no_box_shadow" style="position: relative;"> <div class="panel-heading no_border_radius bg-dark set_padding_0"> <div class="discussion_small_round_div pull-right cursor_pointer" id="discussion_declined"></div> </div> <div class="discussion_edit_div"> <ul> <li> <span class="glyphicon glyphicon-trash"></span> Replicate</li> <li><span class="glyphicon glyphicon-trash"></span> Delete</li> <li><span class="glyphicon glyphicon-ban-circle"></span> Deactivate</li> </ul> </div> </div> <div class="panel discussion_panel_div no_background no_box_shadow" style="position: relative;"> <div class="panel-heading no_border_radius bg-dark set_padding_0"> <div class="discussion_small_round_div pull-right cursor_pointer" id="discussion_pending"></div> </div> <div class="discussion_edit_div"> <ul> <li> <span class="glyphicon glyphicon-trash"></span> Replicate</li> <li><span class="glyphicon glyphicon-trash"></span> Delete</li> <li><span class="glyphicon glyphicon-ban-circle"></span> Deactivate</li> </ul> </div> </div>
Praveen's answer is nice but you can also achieve the same without tweaking your HTML. Just add this to your jQuery: $(window).click(function() { //Hide the menus if visible $('.discussion_edit_div').hide('fast'); }); $("#discussion_declined , #discussion_pending").click(function(e) { e.stopPropagation(); var relatedDiv = $(this).closest('.panel').find('.discussion_edit_div'); relatedDiv.toggle("fast"); $('.discussion_edit_div').not(relatedDiv).hide('fast'); }); And your are good to go. This achieves one more thing which is that once you have opened one ul, then you can directly toggle to another ul by clicking once. In Praveen's answer you have to click twice in order to open the other ul. Check the link:https://jsfiddle.net/zfqqqr1c/1/
How Bootstrap handles this is interesting. They have a mask, and the only thing you can click is the mask or the items in the menu. $(function () { $(".mask").hide(); $("nav > ul > li > a").click(function () { $(this).closest("li").addClass("open"); $(".mask").show(); return false; }); $(".mask").click(function () { $(this).hide(); $(".open").removeClass("open"); }); }); * {font-family: 'Segoe UI'; margin: 0; padding: 0; list-style: none; line-height: 1; box-sizing: border-box;} body {background-color: #f5f5f5;} a {text-decoration: none; color: inherit;} .mask {position: fixed; top: 0; bottom: 0; right: 0; left: 0; z-index: 8;} nav > ul > li {display: inline-block; position: relative; width: 30%;} nav > ul > li a {display: block; padding: 5px; border: 1px solid #ccc;} nav > ul ul {position: absolute; left: 0; right: 0; z-index: 9; display: none;} nav > ul > li.open > ul {display: block;} <script src="https://code.jquery.com/jquery-2.2.4.js"></script> <div class="mask"></div> <nav> <ul> <li> Main Item 1 <ul> <li>Sub Item 1</li> <li>Sub Item 2</li> <li>Sub Item 3</li> <li>Sub Item 4</li> <li>Sub Item 5</li> </ul> </li> <li> Main Item 2 <ul> <li>Sub Item 1</li> <li>Sub Item 2</li> <li>Sub Item 3</li> <li>Sub Item 4</li> <li>Sub Item 5</li> </ul> </li> <li> Main Item 3 <ul> <li>Sub Item 1</li> <li>Sub Item 2</li> <li>Sub Item 3</li> <li>Sub Item 4</li> <li>Sub Item 5</li> </ul> </li> </ul> </nav>
Accordion with multiple links
I'm taking this CSS-Tricks article and converting it to a UL > LI instead of a DT > DD approach. I just want the pink box to reveal the sub-links when clicked. For some reason though I cannot get it working. I've created a jsFiddle of it here (click the pink box): //Accordion (function($) { var allPanels = $('ul.sub-level').hide(); $('.click-me').click(function() { allPanels.slideUp(); alert('slide up'); // Problem line $(this).parent().next().slideDown(); return false; }); })(jQuery); ul { list-style: none; padding:0; margin:0; width: 400px; } ul li { position:relative; background: #fafafa; margin-bottom:3px; height:20px; } ul li > ul { margin-left: 30px; background: #e3e3e3; } .click-me { display:block; width: 20px; height: 20px; position: absolute; top:0; right:0; background: #e4f; cursor: pointer;} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>Link somewhere</li> <li>Link somewhere</li> <li class="test"> Link somewhere <!-- I want to reveal accordion using this span tag --> <span class="click-me"></span> <!-- /end --> <ul class="sub-level"> <li>Link 1</li> <li>Link 2</li> <li>Link 3</li> <li>Link 4</li> </ul> <li>Link somewhere</li> </li> </ul> http://jsfiddle.net/ndczc728/1/ The problem line is this (I think): // Problem line $(this).parent().next().slideDown(); Anyone?
You don't need to use parent. Also you have to remove fixed height from li elements: //Accordion (function($) { var allPanels = $('ul.sub-level').hide(); $('.click-me').click(function() { allPanels.slideUp(); // Problem line $(this).next().slideDown(); return false; }); })(jQuery); ul { list-style: none; padding: 0; margin: 0; width: 400px; } ul li { position: relative; background: #fafafa; margin-bottom: 3px; } ul li > ul { margin-left: 30px; background: #e3e3e3; } .click-me { display: block; width: 20px; height: 20px; position: absolute; top: 0; right: 0; background: #e4f; cursor: pointer; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>Link somewhere </li> <li>Link somewhere </li> <li class="test"> Link somewhere <!-- I want to reveal accordion using this span tag --> <span class="click-me"></span> <!-- /end --> <ul class="sub-level"> <li>Link 1 </li> <li>Link 2 </li> <li>Link 3 </li> <li>Link 4 </li> </ul> <li>Link somewhere </li> </li> </ul>
Horizontal Javascript menu error
I have a small problem with my JavaScript menu. When I choose an item it shows me always the last sub menu. This is very simple for people who are professionals in Javascript :p Here is the sample: CSS ul#midnav { border-width: 1px 0; list-style: none; margin-bottom: 5px; text-align: center; border-bottom: solid thin #c8c8c8; padding: 0px 0px 13px 0px; } ul#midnav li { display: inline; padding: 0px 0px; } ul#midnav li a { text-transform:uppercase; font-size:11px; padding: 5px 13px 0px 5px; background: url('../image/arrow-topdown-gray.png') 100% 9px no-repeat; } ul#midnav li ul { line-height: 28px; padding: 0; position: absolute; top: -30px; background: none; display: none; /* --Hide by default--*/ width: 960px; height:28px; background: #fff; border-top: solid thin #eeeeed; } ul#midnav li ul a { background: url('../image/arrow-left-gray.png') 100% 9px no-repeat; } HTML <div id="navigation"> <div id="mid-nav"> <ul id="midnav"> <li>Item 1 <ul> <li>Item 1.1 </li> <li>Item 1.2 </li> </ul> </li> <li>Item 2 <ul> <li>Item 2.1 </li> <li>Item 2.2 </li> </ul> </li> <li>Item 3 <ul> <li>Item 3.1 </li> <li>Item 3.2 </li> </ul> </li> <li>Item 4 <ul> <li>Contact Us </li> <li>Item 4.1 </li> <li>Item 4.2 </li> </ul> </li> <li>Item 5 <ul> <li>Item 5.1 </li> <li>Item 5.2 </li> </ul> </li> </ul> </div> </div> </div> JavaScript $(document).ready(function () { $('ul#midnav li a').on('click', function (event) { event.preventDefault(); $('#mid-nav > ul').find('ul').slideUp(function () { $(this).closest('li').find('ul').slideToggle(); }); }); });
this in your ready handler refers to the wrong object: $(document).ready(function () { $('ul#midnav li a').on('click', function(event){ event.preventDefault(); var e=this; // must alias or 'this' will refer to // the last submenu slid into hiding // instead of the one to open $('#mid-nav > ul').find('ul').slideUp( function(){ $(e).closest('li').find('ul').slideToggle(); // 'e' instaed of 'this' }); }); });