JS pop-up for different items on page - javascript

I'm trying to make a pop-up for each item in my app to select quantity.
So it preloads several items on page, and I need to make it show pop-up when clicked on any of them.
I found this solution and tried it:
<div class="items">
<div class="menu_item_btn" href = "javascript:void(0)" onclick = "itemquantity()">
<%= item.name %>
</div>
<div id="light" class="itemshowcontent">
<p>Some content</p>
Close
</div>
<div id="fade" class="blackoverlay"></div>
</div>
where js:
<script>
function itemquantity() {
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block'
}
function closeitemquantity() {
document.getElementById('light').style.display='none';
document.getElementById('fade').style.display='none'
}
</script>
It works, however when I select quantity, it always selects it only for the first item that comes.
If click on second item (or any other), the pop-up is still for the first one.
I believe this is because I use getElementById, as ID is used for only one object.
I tried changing to getElementsByClassName, but then it doesn't work at all. So, my question is how to make it work?
Should I stick to using classes? Or somehow use ID, within classes?
I apologise if it's simple question, I'm not really familiar with JS.
Any advice appreciated.
EDIT:
Here are some images for what I'm doing. This is page with listed objects:
These are the objects preloaded from DB shown in a list. When you click on any of them, this pop-up comes up:
to select quantity.
I'm developing in elixir and phoenix framework.

Give id to each item and move light and fade out from id and to class. Then, find light and fade by item id when click function is executed. See the following example.
function getParent(itemChild) { // Get parent.
var item = itemChild.parentElement;
return item;
}
function itemquantity(itemChild) {
var item = getParent(itemChild); // Get parent and it is the item.
item.querySelector('.light').style.display='block'; // Find .light element as of item.
item.querySelector('.fade').style.display='block'; // Find .fade element as of item.
}
function closeitemquantity(itemChild) {
var item = getParent(getParent(itemChild)); // You have to get parent twice and that is the item.
item.querySelector('.light').style.display='none'; // Find .light element as of item.
item.querySelector('.fade').style.display='none'; // Find .fade element as of item.
}
<div class="items" id="apple">
<div class="menu_item_btn" href = "javascript:void(0)" onclick = "itemquantity(this)">
Apple
</div>
<div class="light itemshowcontent">
<p>Red Apple</p>
Close
</div>
<div class="fade blackoverlay"></div>
</div>
<div class="items" id="banana">
<div class="menu_item_btn" href = "javascript:void(0)" onclick = "itemquantity(this)">
Banana
</div>
<div class="light itemshowcontent">
<p>Yello Banana</p>
Close
</div>
<div class="fade blackoverlay"></div>
</div>

Related

how to toggle a specific div in javascript

i have dynamic data in my rails view, all divs have the same name; 'allData', which has alot of info, so i have it not displayed, i want to display that specific div and not all divs when i click show, but it shows all divs, i want to be able to show just that target div i clicked
$('.show'').on('click', (event) =>{
$('.allData').toggle();
$(event.currentTarget).closest('.allData').toggle();
})
<div class='eachData'>
<div class='header'>
<div class='show'> show</div>
<div class='numberOfdata'> 100</div>
</div>
<div class='allData; display:none'>
"foobar all data is here"
</div>
</div>
<div class='eachData'>
.......
</div>
<div class='eachData'>
.......
</div>
Your closest call is on the right track but you're not quite using it right. First you want to find the container (.eachData) that contains your <div class="show">, you use closest for that:
let container = $(event.currentTarget).closest('.eachData');
then you search within that container for the .allData you want to toggle by using find:
container.find('.allData').toggle();
So you use closest to go up the node tree and then find to come back down.
BTW, this:
<div class='allData; display:none'>
should be:
<div class="allData" style="display: none">
The class attribute contains CSS class names delimited by whitespace, raw CSS goes in the style attribute and is delimited by semicolons.
Your inline style on the div should be as follows:
<div class="allData" style="display: none">
Then try the following:
$('.show').on('click', function() {
$(document).find('.eachData .allData:visible').hide('fast');
$(this).parent().closest('.allData').show('fast');
});

Javascript modal that displays list that closes and returns to main html

Rather new to javascript, jquery and bootstrap, etc., so bear with me. I have a situation where I want to present a list of errors in a model dialog after the user hits a "validate" button. Got all the working - I am generating a list of objects that indicate to the user they need more work to the exact spot that needs additional data entry. I have the the DIV "id" that represents the field that needs more data (and each item will jump someplace different).I do not want a drop down list since there are be lots and lots of these items.
A few questions:
How do I go about jumping from the modal to the main html. I believe I have seen scrollIntoView mentioned in a few other posts as I was looking but will that hop to the DIV and also close the modal?
What construct should I use for the list? A list of scrolling button? The size of this can be quite large (hundreds) so it will need a scroll capability.
Finally, the app is "paged" with a next and prev buttons. I assume that will not be a problem from the aspect of jumping to a page not already displayed?
Here is the current modal code:
<script id="template-validation-error" type="text/x-handlebars-template">
<div id="validationErrorModal" class="modal">
<div class="message-container">
<div class="header">
Validation Errors
</div>
<div class="message">
The following fields are required:
</div>
<div class="center">
<input type="button" class="btn btn-solid-green btn-sm" onclick="fffdevice.validationErrorOk();" value="Done" />
</div>
</div>
</div>
</script>
and
showValidationError: function (fieldlist) {
settings.focusedField = $(':focus');
$("#validationErrorModal").detach();
$(".device-container").append(templates.validationerror({ fieldlist }));
$(".message-container input").focus();
},
validationErrorOk: function () {
$("#validationErrorModal").detach();
if (settings.focusedField) {
settings.focusedField.focus();
}
},
The field list is a list of objects that contain the id (field.id) of the DIV and also a description (field.fieldName) that I want to display.
Here is something I mocked up in paint...I am not sold on it but it show in a general sense what I am looking for:
I don't need a full solution rather, just want mechanisms I can use.
UPDATE
Just to help out anyone else in the future, using the info provided in the correct answer below I have a new code as follows:
<script id="template-validation-error" type="text/x-handlebars-template">
<div id="validationErrorModal" class="modal">
<div class="validation-container">
<div class="header" align="center">
Validation Errors
</div>
<div class="message">
<div class="scrolling-container" style="background-color: rgb(238, 238, 238); height:660px">
<div class="grid grid-pad">
{{#each fieldlist}}
<div class="row click-row" onclick="fffdevice.validationErrorFix('{{id}}');">
<div class="col-7-8 field-name">{{fieldName}}</div>
<div class="col-1-8">
<img class="pull-right" src="/mysite/Content/device/images/fix.png" style="width: 40px; position:relative; top: -5px;">
</div>
</div>
{{/each}}
</div>
</div>
</div>
<div><br/></div>
<div class="center">
<input type="button" class="btn btn-solid-green btn-sm" onclick="fffdevice.validationErrorOk();" value="Done" />
</div>
</div>
</div>
Then the Javascript for the onClick is:
validationErrorFix: function (id) {
$("#validationErrorModal").detach();
var x = document.getElementById(id);
x.scrollIntoView({
behavior: "smooth", // or "auto" or "instant"
block: "start" // or "end"
});
},
Which closes the dialog and jumps to the field. It looks like (I know this is ugly and I will clean it up later):
Bind the modal event to the validation code and show the modal if error(s) are found.
Display the modal with the list of errors using an html unordered list, inside the li element an anchor tag where the href attribute will have a value with the id that corresponds to the input field, all this done dynamically from your validation code.
Once an error in the list is clicked hide the modal using bootstrap $('#your-error-modal').modal('hide'); so the code would be something like this:
$('#your-error-modal').on('click', 'a.error-item', function(){
$('#your-error-modal').modal('hide');
});
I haven't tested this code, but if you're having issues with scrolling to the section of the input and closing the modal you can probably do something like this too:
$('#your-error-modal').on('click', 'a.error-item', function(e){ // use this method of onclick because your list will be created dynamically
e.preventDefault(); // prevent the default anchor tag action
var href = $(this).attr('href'); // grab the href value
$('#your-error-modal').modal('hide'); // close the modal first
scrollToDiv(href); // then take the user to the div with error with a nice smooth scroll animation
});
function scrollToDiv(location) {
$('html, body').animate({
scrollTop: $(location).offset().top
}, 2000);
}
Again this is untested code, but the idea is there.
For UX reasons you might also want to create a floating div or something where users can click on it and go back to the modal to continue reading your list of errors.

Find instance following given element

I have a question about dom navigation with jquery. I'm trying to find an element with a given class that is closest in the dom following a given element.
I have a table like structure, created through divs and styled in css. I have an element being edited, and when the user presses enter I want to focus the following editable element. However, it's not a sibling of the element being edited.
HTML
<div class="calendarEntry">
<div when="2014,9,18" class="when">Sep 18</div>
<div class="items">
<div class="item">
<div code="ABC" class="type">ABC123</div>
<div offered="2014,9,15" class="offered dateish">Sep 15
<div class="offer editable">10</div>
<div class="sku editable">TH1</div>
<button>Publish</button>
</div>
</div>
<div class="item">
<div code="DEF" class="type">DEF321</div>
<div offered="2014,9,14" class="offered dateish">Sep 14
<div class="offer editable">10</div>
<div class="sku editable">TH2</div>
<button>Publish</button>
</div>
</div>
<div class="item">
<div code="GHI" class="type">GHI852</div>
<div offered="2014,9,12" class="offered dateish">Sep 12
<div class="offer editable">10</div>
<div class="sku editable">TH3</div>
<button>Publish</button>
</div>
</div>
</div>
</div>
Note: There are multiple calendar entries on the page.
Say the user is editing the offer of the DEF312 item. When they hit enter I want to edit the offer of GHI852. I have the code to make the div editable, by replacing it with a text field with a class of offer editing. If they're editing the final offer in this calendar entry, then the enter key should focus the first editable offer of the following calendar entry, if there is one. If we're at the bottom of the list I don't want to wrap back to the top (which I think would overly complicate matters anyway).
The bit I'm stuck with is how to find the next offer (all offers are editable).
Here's what I've tried:
var nextOffer = $('.offer').find('.editing').next('.editable');
Clearly, this doesn't work. The problem is that the following editable offer isn't a sibling of the current offer being edited, so next() doesn't work for me. The following offer could be in the current calendar entry, or it's just as likely to be in the next calendar entry. Either way, it's a few divs away, at varying depths.
Can I even do this with jquery dom traversals, or am I better just brute forcing it through javascript (i.e. looping through all .editable instances and returning the one after .editing?
Adding the class 'editing' to simulate the the input:
<div class="item">
<div code="DEF" class="type">DEF321</div>
<div offered="2014,9,14" class="offered dateish">Sep 14
<div class="offer editable">10</div>
<div class="sku editable editing">TH2</div>
<button>Publish</button>
</div>
</div>
you can do:
function findEditable(currentItem) {
var nextEditable = undefined,
selectors = [".item", ".calendarEntry"];
$.each(selectors , function (idx, selector) {
var ref = currentItem.closest(selector);
nextEditable = ref.parent()
.children("div:gt(" + ref.index() + ")")
.find(".offer.editable")
.first();
return nextEditable.length === 0;
})
return nextEditable;
}
findEditable($(".editing")).css({
color: 'red'
});
jsfiddle demo
You can use parents() to get the .offered element which contains the .offer element like so:
var offered = $('.offer').find('.editing').parents('.offered');
From that you can use next() to get into the .offered element's sibling .item element, and find the .editable element within that:
offered.next('.item').find('.editable');
JSFiddle demo. Note that I've manually added this .editing element within your DEF321 item's .offer element - I assume this gets added dynamically on your side, but either way isn't included in your question.
Edit: The HTML in the question has now been changed. Based on this, instead of getting the .offered parent, you'd get the .item parent:
var item = $('.offer').find('.editing').parents('.item');
And proceed in the same way as before:
item.next('.item').find('.editable');
JSFiddle demo.
try this
var current=document.activeElement,
all=$(".editable"),
index=all.indexOf(current),
next=all[index+1]
It first finds the current element and the list of elements,
then it will find the current element in the list.
It will then add 1 to the index and select it from the list.
To extend the array with the indexOf function;
if(!Array.prototype.indexOf){
Array.prototype.indexOf=function(e/*,from*/){
var len=this.length>>>0,
from=Number(arguments[1])||0;
from=(from<0)?Math.ceil(from):Math.floor(from);
if(from<0)from+=l;
for(;from<len;from++){
if(from in this&&this[from]===e)return from;
}
return -1;
};
}

jQuery Masonry remove function example

I have implemented jQuery masonry to our site and it works great. Our site is dynamic and users must be able to add/remove masonry box's. The site has an add example but no remove example. Our db is queried returning x number of items. Looping through they are loaded and displayed. Here's a code sample: (we are use F3 framework and the F3:repeat is it's looping mechanism.).
<div id="container" class="transitions-enabled clearfix" style="clear:both;">
<F3:repeat group="{{#productItems}}" value="{{#item}}">
<div id="{{#item.itemId}}">
<div class="box">
<div class="view"> <!-- for css -->
<a onclick='quickRemove("{{#item.itemId}}")>
<img src="{{#item.pic}}" />
</a>
</div>
<p>
{{#item.title}}
</p>
</div>
</div>
</F3:repeat>
</div>
In the javascript code the item id number is unique and is passed into the function. It's also the div id# to distinguish each box. I've tried various combinations and methods but can't seem to get this to work.
function quickRemove(item){
var obj = $('#'+item+'').html(); // item is the product id# but also the div id#
$('#container').masonry('remove',obj);
$('#container').masonry('reloadItems');
$('#container').masonry('reload');
}
Has anyone out there successfully removed an item and how did you do it?
Thx.
Currently you appear to be passing a string full of html to the masonry remove method. Pass it the actual jQuery wrapped element by not including .html()
function quickRemove(item){
var obj = $('#'+item+''); // item is the product id# but also the div id#
$('#container').masonry('remove',obj);
$('#container').masonry('reloadItems');
$('#container').masonry('reload');
}

multiple onclick's in HTML

I have a an HTML page with a list of 20 topics on it. I would like it so that when you click on one of those topics, 2 or 3 articles with links pop up underneath it.
I'm trying onclick but it means writing lots of code as you have to declare all the div styles for each of my topics.
Is there an easy way of doing this?
im currently writing this 20 times, and declaring 60 div styles:
<div class = "mousehand"
id = "show_first"
onclick ="this.style.display = 'none';
document.getElementById('show_second').style.display='block';
document.getElementById('dropdown').style.display='inline';
"> show text </div>
<div class = "mousehand"
id = "show_second"
onclick ="this.style.display = 'none';
document.getElementById('show_first').style.display='block';
document.getElementById('dropdown').style.display='none';
"> hide text </div>
<div id ="dropdown"> this is the text to be shown</div>
You can accomplish this with some Javascript. Add a ul within the li:
<li>Title
<ul>
...
</ul>
</li>
Set the inner ul's display to none using CSS. Then using Javascript, make a function that changes the display property of the inner ul to block.
As has been mentioned, jQuery can make this very straightforward, but your major code saving is going to come from taking advantage of event bubbling. You can do this is you structure your HTML something like this:
<div id="topics">
<div class="item">
<div class="show">
show text 1
</div>
<div class="hide">
hide text 1
</div>
<div class="text">
this is the text to be shown 1
</div>
</div>
<div class="item">
<div class="show">
show text 2
</div>
<div class="hide">
hide text 2
</div>
<div class="text">
this is the text to be shown 2
</div>
</div>
</div>
Now instead of attaching an onclick handler to each end every div, attach it to the parent element. To do this with jQuery:
$(window).load(function(){ //Do this when the page loads
$('#topics').bind('click', function(event) { //Find the element with ID 'topics' and attach a click handler
var t = $(event.target); //event.target is the element that was actually clicked, $() gets the jQuery version of it
if(t.hasClass('show')) { //If it is a 'show' element...
t.siblings('.hide').show(); //...show the other two elements...
t.siblings('.text').show();
t.hide(); //...and hide the clicked element
}
if(t.hasClass('hide')) { //If it is a 'hide' element...
t.siblings('.show').show(); //...show the 'show' element...
t.siblings('.text').hide(); //...and hide the other two
t.hide();
}
});
});
And that's it! Here's a demo.

Categories

Resources