Manipulating original elements with qTip - javascript

I have a bunch of divs on my page and each of them has only the class attribute. In the divs there are some spans, which are set up to display a tooltip with the help of qTip.
The tooltip should contain three items:
Up: anchor, which should move the OuterDiv up (probably something like this: move up/down in jquery)
Down: anchor, which should move the OuterDiv down
Delete: anchor, which should remove the calling OuterDiv
My code so far:
<body>
<div class="OuterDiv">
<div class="InnerDiv">
<span class="Position">Position 1</span>
</div>
</div>
<div class="OuterDiv">
<div class="InnerDiv">
<span class="Position">Position 2</span>
</div>
</div>
</body>
And scripts:
$(document).ready(function () {
var qTipContent = '↑ ';
qTipContent = qTipContent + '↓ ';
qTipContent = qTipContent + 'X';
$('.Position').each(function () {
$(this).qtip({
content: qTipContent,
hide: {
fixed: true
}
})
});
});
How should the onclick function in the qTip content look like?

My solution can be found at this jsFiddle - Besides cleaning up the qTipContent (was just really messy), the only real notable addition was adding ids to the anchors, and using the qTip api to add bindings to the click event for each anchor as the qTip window is added.
$('.Position').each(function(idx, elem) {
$(this).qtip({
content: qTipContent,
show: {
when: {
event: 'click'
}
},
hide: {
fixed: true,
when: {
event: "unfocus"
}
},
api: {
onRender: function() {
var $qtip = $(this.elements.content);
var odiv = $(elem).closest(".OuterDiv");
$("#up_arrow", $qtip).click(function() {
odiv.insertBefore(odiv.prev());
})
$("#down_arrow", $qtip).click(function() {
odiv.insertAfter(odiv.next());
})
$("#delete", $qtip).click(function() {
odiv.remove();
})
}
}
})
});

Related

Jquery click event is not getting triggered

Have been trying to perform a DIV hide show on a page of my website.
It was working fine with plain javascript but noticed it was not working when simulated on mobile devices..after bit of research I changed my code to the following, is there anything wrong in it ?
<script>
$(document).ready(function() {
var portfolioDiv = document.getElementById('portfolio');
var resultsDiv = document.getElementById('results');
var portfolioBtn = document.getElementById('RenderPortfolio_Btn');
var resultsBtn = document.getElementById('RenderResults_Btn');
//portfolioBtn.onclick = function () resultsBtn.onclick = function ()
$('#portfolioBtn').on('click touchstart', function() {
resultsDiv.setAttribute('class', 'col-md-9 hidden');
portfolioDiv.setAttribute('class', 'col-md-9 visible');
});
$('#resultsBtn').on('click touchstart', function() {
portfolioDiv.setAttribute('class', 'col-md-9 hidden');
resultsDiv.setAttribute('class', 'col-md-9 visible');
});
});
</script>
Here is my navbar stack, where the two options act as buttons
<div class="col-md-3 col-sm-12 col-xs-12">
<br />
<ul class="nav nav-stacked">
<li style="background-color: lightgreen ; color:black;font-weight:bold">Introduction
</li>
<li style="background-color: lightgreen; color:black;font-weight:bold">Key Achievements
</li>
</ul>
</div>
You are confusing variables that reference elements with jQuery selectors that select by ID. Essentially you can remove the following lines:
var portfolioBtn = document.getElementById('RenderPortfolio_Btn');
var resultsBtn = document.getElementById('RenderResults_Btn');
and then change your jQuery selectors to:
$('#RenderPortfolio_Btn').on('click touchstart', function() {
and
$('#RenderResults_Btn').on('click touchstart', function() {
Your code is missing a comma between click and touchstart
also you id selector is incorrect
$('#RenderPortfolio_Btn').on('click, touchstart', function() {
resultsDiv.setAttribute('class', 'col-md-9 hidden');
portfolioDiv.setAttribute('class', 'col-md-9 visible');
});

Set Element active and the other inactive (dynamic)

I have a listbox
<div id="listboxid1" class="listboxFilters">
<div class="listboxFilterItem"> <div style="padding-top:2px; float: left;">test2</div> <div class="listboxChosenFilter">3</div> </div>
<div class="listboxFilterItem"> <div style="padding-top:2px; float: left;">test</div> <div class="listboxChosenFilter">*</div> </div>
<div class="listboxFilterItem"> <div style="padding-top:2px; float: left;">gro</div> <div class="listboxChosenFilter">2</div> </div>
</div>
its a normal listbox, the question is now , how can I only set one element to active , and the others then to inactive
my first guess was an onlick on an item, I add a classname named active and before I would do a foreach for the listboxid1 element and set all to inactive, but is this really the common and best way?? :
<script>
function clearAll(element) {
element.each(function () {
var checkboxes = $(this).children("div");
checkboxes.each(function () {
var checkbox = $(this);
checkbox.removeClass("active");
});
});
}
jQuery.fn.multiselecter = function () {
$(this).each(function () {
var checkboxes = $(this).children("div");
checkboxes.each(function () {
var checkbox = $(this);
checkbox.click(function () {
clearAll(checkbox.parent());
checkbox.addClass("active");
});
});
});
};
$("#listbox1").multiselecter();
</script>
I guess you are using jQuery, so try this functions:
On click on anyitem with class .listboxFilterItem call setActive function
$('.listboxFilterItem').click(setActive($(this)));
function setActive(var elem){
$('.listboxFilterItem').each(function(){
$(this).removeClass('active');
});
elem.addClass('active');
}
Try this:
$(".listboxFilterItem").click(function (e) {
$(".listboxFilterItem").removeClass("active");
// or $(".active").removeClass("active");
$(this).addClass("active");
});
Check this on jsfiddle
$(this) - element, which was clicked
$(this).siblings() - all his neighbours, except himself.
$(".listboxFilterItem").click(function () {
$(this).addClass("active").siblings().removeClass("active");
});

smooth transition with show/hide jquery functions on hover?

I'm using an image map and when certain part of image is hovered it show div..(like in this website http://jquery-image-map.ssdtutorials.com/) I want the div to appear with smooth transitions... here is my js code
var mapObject = {
hover : function(area, event) {
var id = area.attr('name');
if (event.type == 'mouseover') {
$('.' + id).show();
$('#'+ id).siblings().each(function() {
if ($(this).is(':visible')) {
$(this).hide();
}
});
$('#'+ id).show();
} else {
$('.' + id).hide();
$('#'+ id).hide();
$('#room-0').show();
}
}
};
$(function() {
$('area').live('mouseover mouseout', function(event) {
mapObject.hover($(this), event);
});
});
Can anyone please suggest me the changes for smooth transitions...
thanks in advance! :)
So first of all, an unrelated tip - it would be a good idea to update jQuery a bit (if there isn't anything that depends on the old version you are using). live won't be available, instead you'll need to replace it with .on, but otherwise it's a good idea.
Secondly, sounds like all you're looking for is to give hide and show some transition. You can simply replace them with fadeIn() and fadeOut(). You can also use toggle which does it all at once (though might misbehave when used with a hover, because it will flip like crazy).
Here's a small snippet that shows you how they work:
$(document).ready(function() {
var img = $('img');
$('#show').on('click', function() {
img.fadeIn();
});
$('#hide').on('click', function() {
img.fadeOut();
});
$('#toggle').on('click', function() {
img.fadeToggle();
});
});
* { font-family: sans-serif; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="show"> Show me! </button>
<button id="hide"> Hide me! </button>
<button id="toggle"> Toggle me! </button>
<br>
<br>
<img src="http://www.randomwebsite.com/images/head.jpg" />
Of course, those are just shortcut functions that use the .animate functionality, which is quite flexible on its own. Here's a link where you can read more about effects and animations in jQuery and how you can use them
Echoing what yuvi said, the 'live' function is deprecated.
I'm not sure why you have your hover function inside an object, but you could also do it like this, using fadeTo:
var mapObject = {
hover : function(area, event) {
var id = area.attr('name');
if (event.type == 'mouseover') {
$('#'+ id).fadeTo(1000, 1.0);
} else {
$('#'+ id).fadeTo(1000, 0);
}
}
};
$(function() {
$('.area').bind('mouseover mouseout', function(event){
mapObject.hover($(this), event);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="area" name="div1" style="width:20px;height:20px;background-color:#CCC;margin:5px;"></div>
<div class="area" name="div2" style="width:20px;height:20px;background-color:#CCC;margin:5px;"></div>
<div id="div1" style="width:150px;height:100px;background-color:#0F0;display:none;margin:5px;">Image Stand-in One</div>
<div id="div2" style="width:150px;height:100px;background-color:#0F0;display:none;margin:5px;">Image Stand-in Two</div>
function smooth(){
if($("#show").is(":visible")){
$("#show").hide("1000");
}
else{
$("#show").show("1000");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click me<br><br>
<h1 id = "show">Shown!</h1>

Removing a div on button click - issue: removing all divs

On a button click event a new div is created. A user can create as many divs as possible. Once a div is created it becomes draggable thanks to the help of the jqueryui draggable PLUGIN. I have set another on click button event that removes the created div. The problem is that when clicking the user clicks the remove button it removes all divs. How can append a button to each div that specifically removes that div? JSFIDDLE
Jquery
/** Remove newly created div **/
$(".remove").click(function(){
$(".draggable").remove();
});
var z = 1;
$('#button').click(function (e) {
/** Make div draggable **/
$('<div />', {
class: 'draggable ui-widget-content',
text: $('textarea').val(),
appendTo: '.middle-side',
draggable: {
containment: 'parent',
start: function( event, ui ) {
$(this).css('z-index', ++z);
}
}
}).addClass('placement');
/** Contain draggable div **/
$('.middle-side').parent().mousemove(function(e){
var offset = $(this).offset();
var relX = e.pageX - offset.left;
var relY = e.pageY - offset.top;
$('.placement').css({'top': relY + 30,'left': relX + 10, 'position': 'absolute'});
})
});
HTML
<textarea rows="4" cols="50" placeholder="Enter Text Here!"></textarea><br/>
<input type="button" id="button" value="Add Div with Text" />
<button class="remove">Remove div</button><br/>
<div>
<div class="middle-side empty"></div>
</div>
Turn the text property to html:
html: '<span class="close">[X]</span><span class="text">' + $('textarea').val() + '</span>',
Then write click event for .close elements:
$('body').on('click', '.draggable .close', function () {
$(this).closest('.draggable').remove();
});
jsFiddle Demo.
Modify your Add Div Button and Remove Button event like this:
$(".remove").click(function(){
$(".currentDiv").remove();
});
var z = 1;
$('#button').click(function (e) {
$(".currentDiv").removeClass("currentDiv");
/** Make div draggable **/
$('<div />', {
class: 'draggable ui-widget-content',
text: $('textarea').val(),
appendTo: '.middle-side',
draggable: {
containment: 'parent',
start: function( event, ui ) {
$(this).css('z-index', ++z);
},
drag: function() {
$(".currentDiv").removeClass("currentDiv");
$(this).addClass("currentDiv");
},
}
}).addClass('placement currentDiv');
In this way when you create a new div, all currentDiv classes are removed in this line:
$(".currentDiv").removeClass("currentDiv");
Then the currentDiv class is added in created div in last line. So always the last created div has currentDiv class.
Then add this block at the end of your JS:
$('body').on('click', '.draggable', function () {
$(".currentDiv").removeClass("currentDiv");
$(this).addClass("currentDiv");
});
The above block cause that when you click on each draggable element, it selected as current div so Remove button, remove that.
Check JSFiddle Demo
In demo i have also add a background-color:red for currentDiv, you can remove it.
You can simply add this after draggable event :
var closeBtn = '<a href="#xcv" onclick="$(this).unwrap();$(this).remove();" >close</a>';
$('.placement').append(closeBtn);
JSFIDDLE DEMO

How to bind bootstrap popover on dynamic elements

I'm using Twitter Bootstrap's popover on the dynamic list. The list item has a button, when I click the button, it should show up popover. It works fine when I tested on non-dynamic.
this is my JavaScript for non-dynamic list
$("button[rel=popover]").popover({
placement : 'right',
container : 'body',
html : true,
//content:" <div style='color:red'>This is your div content</div>"
content: function() {
return $('#popover-content').html();
}
})
.click(function(e) {
e.preventDefault();
});
However, It doesn't work well on dynamic list. It can show up when I click the button "twice" and only show up one of list items I click fist time.
MY html:
<ul id="project-list" class="nav nav-list">
<li class='project-name'>
<a >project name 1
<button class="pop-function" rel="popover" ></button>
</a>
</li>
<li class='project-name'>
<a>project name 2
<button class="pop-function" rel="popover" ></button>
</a>
</li>
</ul>
<div id="popover-content" style="display:none">
<button class="pop-sync"></button>
<button class="pop-delete"></button>
</div>
My JavaScript for dynamic:
$(document).on("click", "#project-list li" , function(){
var username = $.cookie("username");
var projectName = $(this).text()
$("li.active").removeClass("active");
$(this).addClass("active");
console.log("username: " +username + " project name: "+projectName );
});
$(document).on("click", "button[rel=popover]", function(){
$(this).popover({
placement : 'right',
container : 'body',
html : true,
content: function() {
return $('#popover-content').html();
}
}).click(function(e){
e.preventDefault();
})
});
//for close other popover when one popover button click
$(document).on("click", "button[rel=popover]" , function(){
$("button[rel=popover]").not(this).popover('hide');
});
I have searched similar problems, but I still can't find the one to solve my problem. If anyone has some ideas, please let me know. Thanks your help.
Update
If your popover is going to have a selector that is consistent then you can make use of selector property of popover constructor.
var popOverSettings = {
placement: 'bottom',
container: 'body',
html: true,
selector: '[rel="popover"]', //Sepcify the selector here
content: function () {
return $('#popover-content').html();
}
}
$('body').popover(popOverSettings);
Demo
Other ways:
(Standard Way) Bind the popover again to the new items being inserted. Save the popoversettings in an external variable.
Use Mutation Event/Mutation Observer to identify if a particular element has been inserted on to the ul or an element.
Source
var popOverSettings = { //Save the setting for later use as well
placement: 'bottom',
container: 'body',
html: true,
//content:" <div style='color:red'>This is your div content</div>"
content: function () {
return $('#popover-content').html();
}
}
$('ul').on('DOMNodeInserted', function () { //listed for new items inserted onto ul
$(event.target).popover(popOverSettings);
});
$("button[rel=popover]").popover(popOverSettings);
$('.pop-Add').click(function () {
$('ul').append("<li class='project-name'> <a>project name 2 <button class='pop-function' rel='popover'></button> </a> </li>");
});
But it is not recommended to use DOMNodeInserted Mutation Event for performance issues as well as support. This has been deprecated as well. So your best bet would be to save the setting and bind after you update with new element.
Demo
Another recommended way is to use MutationObserver instead of MutationEvent according to MDN, but again support in some browsers are unknown and performance a concern.
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
// create an observer instance
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
$(mutation.addedNodes).popover(popOverSettings);
});
});
// configuration of the observer:
var config = {
attributes: true,
childList: true,
characterData: true
};
// pass in the target node, as well as the observer options
observer.observe($('ul')[0], config);
Demo
Probably way too late but this is another option:
$('body').popover({
selector: '[rel=popover]',
trigger: 'hover',
html: true,
content: function () {
return $(this).parents('.row').first().find('.metaContainer').html();
}
});
I did this and it works for me.
"content" is placesContent object. not the html content!
var placesContent = $('#placescontent');
$('#places').popover({
trigger: "click",
placement: "bottom",
container: 'body',
html : true,
content : placesContent,
});
$('#places').on('shown.bs.popover', function(){
$('#addPlaceBtn').on('click', addPlace);
}
<div id="placescontent"><div id="addPlaceBtn">Add</div></div>
Try this HTML
Do Popover 1
Do Popover
<div id="popover-content-1" style="display: none">Content 1</div>
<div id="popover-content-2" style="display: none">Content 2</div>
jQuery:
$(function() {
$('[data-toggle="popover"]').each(function(i, obj) {
var popover_target = $(this).data('popover-target');
$(this).popover({
html: true,
trigger: 'focus',
placement: 'right',
content: function(obj) {
return $(popover_target).html();
}
});
});
});
This is how I made the code so it can handle dynamically created elements using popover feature. Using this code, you can trigger the popover to show by default.
HTML:
<div rel="this-should-be-the-target">
</div>
JQuery:
$(function() {
var targetElement = 'rel="this-should-be-the-target"';
initPopover(targetElement, "Test Popover Content");
// use this line if you want it to show by default
$(targetElement).popover('show');
function initPopover(target, popOverContent) {
$(target).each(function(i, obj) {
$(this).popover({
placement : 'auto',
trigger : 'hover',
"html": true,
content: popOverContent
});
});
}
});
Just to update that, a no-jquery answer for people using bootstrap 5 is
var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
popoverTriggerList.map(function (popoverTriggerEl) {
return new bootstrap.Popover(popoverTriggerEl, {
content: get_content
})
})
The get_content function should use this (the popover element) to generate dynamic content.

Categories