I'm working on a project and I am attempting to create a modal dialog "pop-up" to capture data in a form. I haven't worked with jQuery UI's Dialog widget previously, but I've worked with others and it seemed straight forward.
I created the following very simple code snippet to test as I went along:
<div class="app-email">
<div>
<a href="#"
class="app-email-opener">
Click to add or edit your e-mail settings.
</a>
</div>
<div class="app-email-modal">
Oh, Hai.
</div>
</div>
$('.content').on({
click: function () {
console.log('I was totes clicked.');
var parent = $(this).parents('.app-email');
console.log(parent);
var target = parent.find('.app-email-modal');
console.log(target);
$(target).dialog('open');
}
}, '.app-email-opener');
$('.app-email-modal').dialog({
autoOpen: false,
modal: true,
show: false
});
For reference: the class 'content' is a higher level block to catch delegated events without having to go all the way up the DOM.
The issue I'm running into is that the div with class="app-email-modal" seems to flash onto the page and then disappear from the DOM completely. jQuery, therefore, isn't able to find it and do anything because at that point it simply doesn't exist.
The overall project is in ASP.NET MVC 4, using Visual Studio 2013.
Any information would be greatly appreciated.
So, finally discovered what's happening via this previously answered question:
Jquery Dialog - div disappears after initialization
//EDIT
For any possible future usefuless -
What was happening was that jQuery UI will move any DOM elements specified as Dialogs to the bottom of the page, rather than keep them in the location specified in the HTML markup. So, in my case, I was looking for things by class, but only within the scope of the app-email-openers parent app-email div.
To remedy this, I used templating (in my case, Razor) to add unique ids to each app-email-modal div, and added a data- attribute to associate the link with the specific unique id. This way they jQuery UI can move the elements as it sees fit, but there still easily accessible.
//END EDIT
I feel like that functionality should be better spelled out in the documentation. Even their own example doesn't operate like this.
Corollary: I attempted to use the appendTo option to have the DOM elements not be shifted to the bottom of the page, but they're still moved to the bottom. So, there's that.
Related
I am using Materialize.css on my portfolio site, and am using the npm package clipboard.js. I am using this within a floating action button, and the copy to clipboard functionality is working as intended (when user clicks the button, it copies my email to their clipboard like it should).
However, I want the tooltip to update from ""Click to copy my email to your clipboard!" to a success message like "Copied to your clipboard ✅". I have tried the code below and it won't actually update the page, though I can sometimes see the new message (it's just very inconsistent, which I don't want).
This is my html element:
<li>
<a id="email" data-clipboard-text="example#gmail.com" class="btn-floating red waves-effect waves-light tooltipped" data-position="left" data-tooltip="Click to copy my email to your clipboard!"><i class="material-icons">mail</i></a>
</li>
and here's my javascript:
var clipboard = new ClipboardJS('#email');
clipboard.on('success', function(e) {
var anchorElement = $('#email');
anchorElement.attr('data-tooltip', 'Copied to your clipboard ✅');
anchorElement.addClass('success');
anchorElement.tooltip();
// Reset after a timeout
anchorElement.mouseleave(function() {
setTimeout( function(){
anchorElement.attr('data-tooltip', 'Click to copy my email address to your clipboard!');
anchorElement.removeClass('success');
anchorElement.tooltip();
}, 300);
});
e.clearSelection();
});
I would like for the tooltip to show the updated value consistently, but I haven't been able to figure out what's wrong with the code I have. I can tell that it does update the html element, as I can sometimes see the updated text, but it's very inconsistent and for this feature to be worth using at all I need it to be very consistent.
Any help would be greatly appreciated!
The problem you're running into is that materialize.css adds in other DOM elements that eventually appear on screen as the tooltips themselves - elements that you aren't targeting right now - elements that you didn't write in your HTML. You're targeting the original data-attributes that materialize.css uses to create those other elements. Updating those data-attributes after render is too little too late... by then, the materialize.css library has already looked at those attributes and gotten what it needs.
If you look at the official docs page on tooltips, we can investigate a little on that page. Open your dev console and scroll towards the bottom you'll see four DOM elements with the class material-tooltip - these were added by the library, and these are the DOM elements that actually get shown on screen.
Open those divs up and watch what happens to them when you mouse over the Bottom, Top, Left, Right buttons on the screen. As each tooltip appears, you should notice that the message-to-be-displayed gets injected as text into that element, and it animates some CSS properties.
If you want to change the text being displayed, you can probably skip editing the data-attributes (though if the library occasionally refreshes the content, changing the attributes might still be a good idea)... instead, we need to edit the text being shown in ^^THESE^^ elements.
If you only have one tooltip being displayed on that page, it should be as simple as something like this:
$('.material-tooltip').innerText = 'Copied to your clipboard ✅'
or if you have multiple on that page, you can attempt to identify which div is for which tooltip, but I suspect that could end up being unreliable. It would probably be safer to update ALL of the divs... the library will overwrite the content anyways next time it renders... which again, it gets from your data-attributes. Updating all of them would look something like:
$('.material-tooltip').each( eachDiv => {
eachDiv.innerText = 'Copied to your clipboard ✅'
})
here's only solution I found that works for me .. disclaimer - it's a bit hacky, basically it destroys tooltip on click and rebuilds it with new attr, then after a timeOut resets it back.
$('#shareLink').on('click', function (e) {
$('#shareLink').tooltip('dispose').removeClass('material-tooltip').attr('title', 'Link copied!');
$('#shareLink').addClass('material-tooltip').tooltip('show');
setTimeout( function () {
$('#shareLink').tooltip('dispose').removeClass('material-tooltip').attr('title', 'Copy link to Clipboard');
$('#shareLink').addClass('material-tooltip').tooltip('enable');
}, 2000);
});
I'm currently working on a project in ReactJS. Some of my components are not rendered all the time but change dynamically based on certain conditions. When these components have a tool tip attached to them, I'm noticing that if the tooltip was active when the element was hidden, the tooltip does not go away. I'm looking for a way to remove or at least hide this tooltip when the element is not being rendered.
This is how I'm activating the tooltips using jQuery:
$(document).ready(function() {
$("body").tooltip({ selector: '[data-toggle=tooltip]', placement: 'bottom' })
})
This is how I'm using it within the html (or jsx):
<a className="icon-btn" onClick={ () => {
//on Click I remove this parent element and show something else
}}>
<i className="fa fa-lg fa-pencil-square" title="Edit" data-toggle="tooltip"></i>
</a>
Note I have not been able to select all elements by tooltip using:
$('[data-toggle=tooltip]').tooltip()
Apparently that is because I am adding elements dynamically? At least that is what my research so far shows
$('.tooltip').tooltip('hide');
I was having a similar problem and I know that the question is already a bit old but I post my solution, maybe it helps someone in the future... (It's an Angular-TypeScript-JQuery mixture but the principle is the same.)
In the component:
/* Toggles the Bootstrap 4 tooltip of an HTML element. */
private tooltip(elem: HTMLElement, action: string): void {
(<any>$(elem)).tooltip("dispose");
(<any>$(elem)).tooltip({ container: "body" });
(<any>$(elem)).tooltip(action);
(<any>$(elem)).tooltip("update");
}
In the view:
<someElement data-toggle="tooltip" title="..."
(mouseenter)="tooltip($event.target,'show')"
(mouseleave)="tooltip($event.target,'hide')">
</someElement>
So basically instead of using a global $('[data-toggle=tooltip]').tooltip() for activating all tooltips at once – which wouldn't work anyway if you have tooltips not being part of the DOM at the time this code is called because the page is generated dynamically by some JS framework for example – you only attach the tooltips to the elements when the cursor enters them, and destroy them immediately when it leaves.
(The { container: "body" } and "update" options are only to prevent positioning issues like this for more complex layouts.)
Though this is an older one, this may help someone in future...I encountered this issue in a Vue app and setting the tooltip to hover only did not solve the issue for me (I also wanted it to appear on focus for accessibility reasons). Ultimately, setting data-container to a parent element worked for me which then creates the tooltip inside this element (in my case, the entire parent element was being removed so the tooltip is then removed with it). Note, you may need to set data-boundary to "window" as well if you run into tooltip placement issues - this will ensure it will overflow the container. For example:
<button data-toggle="tooltip" data-placement="right" data-container=".container" data-boundary="window"></button>
None of the accepted answers seemed to resolve my issue, and would just leave the tooltip floating mid-page, and then upon scrolling, it would move to the top left of the page due to the absolute positioning. (I'm using Vue, and the element already had an #click event on it, so I added a parent wrapping div and applied an inline event there)
<div onclick="removeTT()">
<div data-toggle="tooltip" data-placement="top" title="Tooltip on top"></div>
</div>
<script>
function removeTT() {
$('.tooltip').tooltip('hide');
}
</script>
I am trying to create a live HTML editor with AngularJS, where user can drag and drop some DOM elements to a container and it will render the final HTML page, for example, there is a button (or whatever) that says "Drag me to create an input", then user will drag that item into the container and an input field will be rendered...
I've been trying ngDraggable module but isn't what I needed...
I think a way is to hold the HTML code into some $scope variable, and when the user drops the button into the container, $scope.input which contains <input type="text" placeholder="Something"/> will be rendered inside container...
My final step is to enable inline edit to thoose HTML elements generated, in order to let the user create some content agains that final template.
When the user finish, the whole HTML code will be saved somewhere or downloaded...
I don't need something complex, just a few predefined elements that can be dropped...
I hope I've explained it correctly.
There is some example found at http://nboychev.com/tests/angular/Drag%20Drop%20iFrame%20using%20Angular%20JS%20Directive.html that does exactly what I want (see source), BUT:
It's using jQueryUI (Which I don't want to use, but if its needed then I will)
It isn't working on my project. I must say that I'm using RequireJS, but everything works on my angular app but the directives mentioned on the link above. Draggable is not working, I do not have any errors and I've checked that the code is being executed, doing some console.log() stuff, but still not working...
But it contains what I want, draggable stuff with HTML injected that renders content on an iframe (or a div, or whatever) and that new content is also droppable, to insert more stuff inside that code. Give it a try, and guide me a little. Thanks
I think it's better if you try using something as jui
On the other hand you can try implementing your own directive:
<br>
<h4>Drop Area</h4>
<div droppable jui-options="{addClasses: false}" class="drop-area"></div>
<div class="read-out">
<span class="text-info"><strong>Draggable ID</strong></span>: {{obj.id}}<br><br>
<span class="text-info"><strong>Content</strong></span>: <span ng-bind-html="obj.content"></span><br><br>
<span class="text-info"><strong>Actual Content</strong></span>: {{obj.content}}<br><br>
</div>
</div>
http://codepen.io/m-e-conroy/pen/jCdhu
Sounds like a fun project.
This is a simple link function using JqueryUI and Angular. You'll need an HTML element in scope with class "draggable". Use destroy() when finished.
Adding HTML to the DOM from the scope, check out this solution by Josh David Miller: http://jsfiddle.net/paulocoelho/fBjbP/2/
Or for simple HTML elements for visual display only you could try using ngBindHtml, ngRepeat and ngSanitize. Then adding / removing HTML elements to and from an array should display them in a container.
link: function($scope, $elem, $attr){
$elem.find(".draggable").draggable({
start: function(event, ui){
$(ui.item).addClass("shadow");
},
stop: function(event, ui){
$(ui.item).removeClass("shadow");
// DO SOME ANGULAR STUFF HERE
}
});
}
I have this AngularJS app. Everything works just fine.
Now I need to show different pop-ups when specific conditions become true, and I was wondering what would be the best way to proceed.
Currently I’m evaluating two options, but I’m absolutely open to other options.
Option 1
I could create the new HTML element for the pop-up, and append to the DOM directly from the controller.
This will break the MVC design pattern. I’m not happy with this solution.
Option 2
I could always insert the code for all the pop-ups in the static HTML file. Then, using ngShow, I can hide / show only the correct pop-up.
This option is not really scalable.
So I’m pretty sure there has to be a better way to achieve what I want.
Based on my experience with AngularJS modals so far I believe that the most elegant approach is a dedicated service to which we can provide a partial (HTML) template to be displayed in a modal.
When we think about it modals are kind of AngularJS routes but just displayed in modal popup.
The AngularUI bootstrap project (http://angular-ui.github.com/bootstrap/) has an excellent $modal service (used to be called $dialog prior to version 0.6.0) that is an implementation of a service to display partial's content as a modal popup.
It's funny because I'm learning Angular myself and was watching some video's from their channel on Youtube.
The speaker mentions your exact problem in this video https://www.youtube.com/watch?v=ZhfUv0spHCY#t=1681 around the 28:30 minute mark.
It comes down to placing that particular piece of code in a service rather then a controller.
My guess would be to inject new popup elements into the DOM and handle them separate instead of showing and hiding the same element. This way you can have multiple popups.
The whole video is very interesting to watch as well :-)
Create a 'popup' directive and apply it to the container of the popup content
In the directive, wrap the content in a absolute position div along with the mask div below it.
It is OK to move the 2 divs in the DOM tree as needed from within the directive. Any UI code is OK in the directives, including the code to position the popup in center of screen.
Create and bind a boolean flag to controller. This flag will control visibility.
Create scope variables that bond to OK / Cancel functions etc.
Editing to add a high level example (non functional)
<div id='popup1-content' popup='showPopup1'>
....
....
</div>
<div id='popup2-content' popup='showPopup2'>
....
....
</div>
.directive('popup', function() {
var p = {
link : function(scope, iElement, iAttrs){
//code to wrap the div (iElement) with a abs pos div (parentDiv)
// code to add a mask layer div behind
// if the parent is already there, then skip adding it again.
//use jquery ui to make it dragable etc.
scope.watch(showPopup, function(newVal, oldVal){
if(newVal === true){
$(parentDiv).show();
}
else{
$(parentDiv).hide();
}
});
}
}
return p;
});
See
http://adamalbrecht.com/2013/12/12/creating-a-simple-modal-dialog-directive-in-angular-js/
for a simple way of doing modal dialog with Angular and without needing bootstrap
Edit: I've since been using ng-dialog from http://likeastore.github.io/ngDialog which is flexible and doesn't have any dependencies.
Angular-ui comes with dialog directive.Use it and set templateurl to whatever page you want to include.That is the most elegant way and i have used it in my project as well.
You can pass several other parameters for dialog as per need.
The code below works fine with ONE Reveal/Hide Text process
<div class="reveal">Click Here to READ MORE...</div>
<div style="display:none;">
<div class="collapse" style="display:none;">Collapse Text</div>
However if this code is duplicated multiple times, the Collapse Text shows up and doesn't disappear and in fact conflicts with the Expand to reveal even more text instead of collapsing as it should.
In this http://jsfiddle.net/syEM3/4/ click on any of the Click Here to READ MORE...
Notice how the Collapse Text shows up at the bottom of the paragraphs and doesn't disappear. Click on the Collapse and it reveal more text.
How do I prevent this and getting to work as it should?
The two slideDown function calls are not specific to the .reveal and/or .collapse that you are currently doing. i.e.
$(".collapse").slideDown(100);
will find all the elements with the class .collapse on the page, and slide them down. irrespective of what element you just clicked.
I would change the slideDown call to be relavant to the element you just clicked i.e. something like this
$('.reveal').click(function() {
$(this).slideUp(100);
$(this).next().slideToggle();
$(this).next().next(".collapse").slideToggle(100);
});
in your code
$('.reveal').click(function() {
$(this).slideUp(100);
$(this).next().slideToggle();
$(".collapse").slideDown(100);
});
$('.collapse').click(function() {
$(this).slideUp(100);
$(this).prev().slideToggle();
$(".reveal").slideDown(100);
});
this two rows doesn’t do what you want as they act on all elements of the specified class
$(".reveal").slideDown(100);
$(".collapse").slideDown(100);
When you do $(".collapse").slideDown(100);, jQuery runs slideDown on everything with the .collapse class, not just the one that's related to your current this. To fix this, refer to the collapse based on its location to $(this).
Do do this, use something like $(this).siblings(".collapse").slideDown(100);
Note that this particular selector will only work if you enclose each text block in its own div. With each text element in its own div, like you have it now, .siblings(".collapse"), which selects all the siblings of $(this) with the collapse class, will still select both of the collapse elements.
Okay, I think you should take a different approach to your problem.
See, jQuery basically has two purposes:
Selecting one or more DOM elements from your HTML page
manipulate the selected elements in some way
This can be repeated multiple times, since jQuery functions are chainable (this means you can call function after function after function...).
If I understood your problem correctly, you are trying to build a list of blog posts and only display teasers of them.
After the user clicks the "read more" button, the complete article gets expanded.
Keep in mind: jQuery selects your elements very much like CSS would do. This makes it extremely easy to
come up with a query for certain elements, but you need to structure your HTML in a good way, like
you would do for formatting reasons.
So I suggest you should use this basic markup for each of your articles (heads up, HTML5 at work!):
<article class="article">
<section class="teaser">
Hey, I am a incredible teaser text! I just introduce you to the article.
</section>
<section class="full">
I am the articles body text. You should not see me initially.
</section>
</article>
You can replace the article and section elements with div elements if you like to.
And here is the CSS for this markup:
/* In case you want to display multiple articles underneath, separate them a bit */
.article{
margin-bottom: 50px;
}
/* we want the teaser to stand out a bit, so we format it bold */
.teaser{
font-weight: bold;
}
/* The article body should be a bit separated from the teaser */
.full{
padding-top: 10px;
}
/* This class is used to hide elements */
.hidden{
display: none;
}
The way we created the markup and CSS allows us to put multiple articles underneath.
Okay, you may have noticed: I completely omitted any "read more" or "collapse" buttons. This is done by intention.
If somebody visits the blog site with javascript disabled (maybe a search engine, or a old mobile which doesn't support JS or whatever),
the logic would be broken. Also, many text-snippets like "read more" and "collapse" are not relevant if they don't actually do anything and are not part of the article.
Initially, no article body is hidden, since we didn't apply the hidden css class anywhere. If we would
have embedded it in the HTML and someone really has no JavaScript, he would be unable to read anything.
Adding some jQuery magic
At the bottom of the page, we are embedding the jQuery library from the google CDN.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
This is a best practice and will normally speed up your page loading time. Since MANY websites are embedding
jQuery through this URL, chances are high that its already in the visitors browser cache and doesn't have
to be downloaded another time.
Notice that the http: at the beginning of the URL is omitted. This causes browsers to use the pages current protocol,
may it be http or https. If you would try and embed the jQuery lib via http protocol on a https website, some browsers will refuse to download the file from a unsecure connection.
After you included jQuery into the page, we are going to add our logic into a script tag. Normally we would
save the logic into a separate file (again caching and what not all), but this time a script block will do fine.
Finally some JavaScript
At first, we want to hide all elements with the css-class full, since only teasers should remain displayed. This is very easy with jQuery:
$('.full').hide();
The beginning of the script $('.full') tells jQuery: I need all elements with the CSS-class full. Then we call a function on that result, namingly hide() which purpose should be clear.
Okay, in the next step, we want to add some "read more" buttons, next to every teaser. Thats an easy task, too:
$('.teaser').after('<button class="more">Read more</button>');
We now select every element with the css-class teaser and append some HTML code after() each element - a button with the css-class more.
In the next step, we tell jQuery to observe clicks on every one of this freshly created buttons. When a user has clicked, we want to expand the next element with the css-class full after the clicked button.
$('.more').on('click', function(){
//"this" is a reference to the button element!
$(this).slideUp().next('.full').slideDown();
});
Phew, what did we do here?
First, we told jQuery that we wanted to manipulate this, which is a reference to the clicked button. Then we told
jQuery to hide that button (since its not needed anymore) slowly with slideUp().
We immediately continued telling jQuery what to do: Now take the next() element (with the css-class full) and make it visible by sliding it down with slideDown().
Thats the power of jQuerys chaining!
Hiding again
But wait, you wanted to be able to collapse the articles again! So we need a "collapse" button, too and
some more JavaScript:
$('.full').append('<button class="collapse">Collapse text</button>');
Note: we didn't use the after() function to add this button, but the append() function to place the button
INSIDE every element with the css-class full, rather than next to it. This is because we want the
collapse buttons to be hidden with the full texts, too.
Now we need to have some action when the user clicks one of those buttons, too:
$('.collapse').on('click', function(){
$(this).parent().slideUp().prev('.more').slideDown();
});
Now, this was easy: We start with the button element, move the focus to its parent() (which is the element that contains the full text) and tell jQuery to hide that element by sliding it up with slideUp().
Then we move the focus from the full-text container to its previous element with the css-class more, which is its expanding button that has been hidden when expanding the text. We slowly show that button again by calling slideDown().
Thats it :)
I've uploaded my example on jsBin.