bpopup multiple - javascript

I'm using a lightweight jQuery popup plugin called 'bPopup'. I'm using it on my website at the moment to load multiple popup windows when clicked. I was recently told that my code was inefficient as I was loading multiple popups with multiple JavaScript 'listeners', i.e.:
<script type="text/javascript">
;(function($) {
$(function() {
$('#my-button_1').bind('click', function(e) {
e.preventDefault();
$('#element_to_pop_up_32754925023').bPopup();
});
});
})(jQuery);
</script>
<script type="text/javascript">
;(function($) {
$(function() {
$('#my-button_2').bind('click', function(e) {
e.preventDefault();
$('#element_to_pop_up_95031153149').bPopup();
});
});
})(jQuery);
^^ The multiple JavaScript 'listeners'. And, for the Popups:
<!-- Button that triggers the popup -->
<a class="main" id="my-button_1" href="#">Popup 1</a></b><br />
<!-- Element to pop up -->
<div id="element_to_pop_up_1">
// ...
</div>
<!-- Button that triggers the popup -->
<a class="main" id="my-button_1" href="#">Popup 1</a></b><br />
<!-- Element to pop up -->
<div id="element_to_pop_up_1">
// ...
</div>
He's probably right (sure of it), but not sure how to implement this, or whether this is even possible (small chance he's wrong).
Help? And thanks!

Since you are using jquery, you should use it's on() method to attach a single listener to the parent DOM element, and use the selector parameter to properly delegate the event to it's children (the button/popups).
If this sounds confusing, a simple example might help:
HTML:
<div id="parent">
Show popup 1
<div id="popup1" class="popup">1</div>
Show popup 2
<div id="popup2" class="popup">2</div>
Show popup 3
<div id="popup3" class="popup">3</div>
Non-popup link
</div>
JS:
$('#parent').on('click', 'a.button', function (event) {
event.stopPropagation();
event.preventDefault();
var popup = $(this).attr('href');
$('#'+popup).bPopup();
});
This adds a single event listener on the parent element, which only gets triggered if the child element which triggered the event matches the selector (in this case a.button). It determines which popup to show by retreiving the popup's id from the href attribute.
You can see this example working here.

The below function ( myFunction() ) takes the Id of anchor/div tag which is clicked and another id of div content to be display. And applies the same style for all popup models. And also it hides the old popup which already opened when u open new popup. All popup properties you can change.
Here i used only for two popups but you can use it for many as same did here.
<script type="text/javascript">
function myFunction(whId,whtDivContent,e) {
//var totWidth = $(document).width();
//var marTop = position.top;
var elt = $(whId);
var position = elt.position();
var marLeft = position.left - 130;
if(marLeft <= 1) {
marLeft = 10;
}
var openModal_profile ='#openModal_profile';
var openModal_menu ='#openModal_menu';
// Prevents the default action to be triggered.
e.preventDefault();
$(whtDivContent).bPopup({
position: [marLeft, 0] //x, y
,opacity: 0.9
,closeClass : 'b-close'
,zIndex: 2
,positionStyle: 'fixed' //'fixed' or 'absolute' 'relative'
,follow: [false,false] //x, y
,onOpen: function() {
if(openModal_profile == whtDivContent) {
$(openModal_menu).bPopup().close();
}
else if(openModal_menu == whtDivContent) {
$(openModal_profile).bPopup().close();
}
$(whId).css({'background-color':"#DFDFDF"});
}
,onClose: function() { $('.close').click(); $(whId).css({'background-color':""}); }
});
}
;(function($) {
// DOM Ready
$(function() {
// From jQuery v.1.7.0 use .on() instead of .bind()
//$(id_menu).on('click',function(e) {}
var id_menu = '#id_menu';
var openModal_menu ='#openModal_menu';
$(id_menu).toggle(function(e) {
//$(id_menu).css({'background-color':"#DFDFDF"});
myFunction(id_menu,openModal_menu,e);
},function(e){
//$(id_menu).css({'background-color':""});
$('.close').click();
$(openModal_menu).bPopup().close();
});
var id_profile = '#id_profile';
var openModal_profile ='#openModal_profile';
$(id_profile).toggle(function(e) {
//$(id_profile).css({'background-color':"#DFDFDF"});
myFunction(id_profile,openModal_profile,e);
},function(e){
//$(id_profile).css({'background-color':""});
$(openModal_profile).bPopup().close();
});
//ENDS HERE
});
})(jQuery);
</script>

Related

Slide down div on click event

I have simple slide down script that shows div on click event. The problem i have is, that onclick event doesn't work if i have it wrapped in another div. If clickable div doesn't have any parent div it works fine.
I'm using this for multiple div's, where only one is opened at once.
I need open 1 to work
Here's Fiddle
HTML
<div>
<div class="clickMore">open 1</div>
</div>
<div class="clickMore">open 2</div>
<div class="showMore" style="display:none;">
<div>text</div>
</div>
JS
$(function() {
$('.clickMore').on('click', function() {
$('.showMore').not($(this).next('.showMore')).slideUp('fast');
$(this).next('.showMore').slideToggle('fast');
});
});
Working fiddle.
The problem happen since you've two cases and the selector $(this).next('.showMore') will not return always the desired result, since when you've the .clickMore element inside a div the .next() function will not find the element because it's outside of the current div?
My suggestion id to add a condition to make sure if the related .showMore element is directly next to the clicked div or it should be targeted by adding the parent :
$(function() {
$('.clickMore').on('click', function() {
if ($(this).next('.showMore').length) {
var show_more = $(this).next('.showMore');
} else {
var show_more = $(this).parent().next('.showMore');
}
$('.showMore').not(show_more).slideUp('fast');
show_more.slideToggle('fast');
});
});
Short version of condition could be :
$(function() {
$('.clickMore').on('click', function() {
var show_more = $(this).next('.showMore');
show_more = show_more.length > 0 ? show_more : $(this).parent().next('.showMore');
$('.showMore').not(show_more).slideUp('fast');
show_more.slideToggle('fast');
});
});
Try this
$(function() {
$('.clickMore').on('click', function() {
$('.showMore').slideToggle('fast');
});
});
Working Fiddle
$(function() {
$('.clickMore').on('click', function() {
$('.showMore').hide();
var el = $(".showMore");
$(".showMore").remove();
$(this).append(el);
$('.showMore').slideToggle();
});
});
You are able to change the text content dynamically

get Contenteditable div html

Jsfiddle at demo.
I have a contenteditable div. I want the html of whatever I write in that div, on the click of anchor tag.
Right now, div is working but nothing is showing on click of the anchor tag.
function getcode()
{
var content = $('#my-contenteditable-div').html();
alert (content);
}
You can do this as well:
$("a").click(function () {
alert($('#my-contenteditable-div').html());
});
Here is the JSFiddle
Then you don't need to write separate functions and attach it to the onclick event attribute of the a tag
Try This
// get the link
var link = document.getElementById("linkId");
// add click listener to it
link.addEventListener("click",getcode,false);
// you handler
function getcode()
{
var content = document.getElementById("my-contenteditable-div");
alert (content.innerHTML);
}
Just you can go with jquery
Working Fiddle
$(document).ready(function() {
$('#gethtml').on('click', function(e) {
var content = $('#my-contenteditable-div').html();
alert (content);
});
});
can use this use id in a and a div to show data
<div contenteditable="true" id="my-contenteditable-div">
sdfsdfds
</div>
<a href="#" id="getcode" >Get HTML</a>
<div id="show"></div>
and jQuery
$( "#getcode" ).click(function() {
var contents = $('#my-contenteditable-div').html();
$("#show").text(contents);
});

Capturing 'shown' event from bootstrap tab

I have some 'static' HTML on my page:
<div id="DIVISIONS">
<ul class="nav nav-tabs" id="DIVISIONTABS">
#* <li> nodes will be injected here by javascript *#
</ul>
<div class="tab-content" id="DIVISIONTABPANES">
#* <div class="tab-pane"> nodes will be injected here by javascript *#
</div>
</div>
On page load, I create a tab 'framework', i.e. create the bootstrap tabs and tab content containers.
I trigger the process with:
$(window).bind("load", prepareDivisionTabs);
And "prepareDivisionTabs" does this:
function prepareDivisionTabs() {
// Retrieve basic data for creating tabs
$.ajax({
url: "#Url.Action("GetDivisionDataJson", "League")",
cache: false
}).done(function (data) {
var $tabs = $('#DIVISIONTABS').empty();
var $panes = $('#DIVISIONTABPANES').empty();
for (var i = 0; i < data.length; i++) {
var d = data[i];
$tabs.append("<li>" + NMWhtmlEncode(d.Name) + "</li>");
$panes.append("<div id=\"TABPANE" + d.DivisionId + "\" class=\"tab-pane\"></div>")
}
renderDivisionTabPaneContents(data);
}).fail(function (err) {
alert("AJAX error in request: " + JSON.stringify(err, null, 2));
});
}
For info, the "renderDivisionTabPaneContents" in the above does this:
function renderDivisionTabPaneContents(data) {
for (var i = 0; i < data.length; i++) {
var d = data[i];
renderDivisionTabPaneContent(d.DivisionId);
}
}
function renderDivisionTabPaneContent(id) {
var $tabPane = $('#TABPANE' + id);
$tabPane.addClass("loader")
$.ajax({
url: "/League/GetDivisionPartialView?divisionId=" + id,
cache: false
}).done(function (html) {
$tabPane.html(html);
}).fail(function (err) {
alert("AJAX error in request: " + JSON.stringify(err, null, 2));
}).always(function () {
$tabPane.removeClass("loader")
});
}
All good so far. My page loads, my tab contents are rendered, and when I click the different tabs, the relevant content is shown.
Now, rather than loading all content at the start, I want to load tab content just-in-time by using the 'shown' event of the tabs. To test this, I've wanted to just make sure I could get a javascript alert when the tab was shown. So, I create the following to trigger the attachment of tab shown events:
$(function () {
attachTabShownEvents();
})
which calls:
function attachTabShownEvents() {
$(document).on('shown', 'a[data-toggle="tab"]', function (e) {
alert('TAB CHANGED');
})
}
I'd therefore expect so see the "TAB CHANGED" alert after the change of tab. But ... I see no alerts.
Could anybody help me out here?
The correct event binding for tab change is shown.bs.tab.
$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
alert('TAB CHANGED');
})
Update 11-01-2020 --- Bootstrap 4.5
This is still the correct answer however, this is a bit of additional helpful information found all the way at the bottom of the official bootstrap docs page at: https://getbootstrap.com/docs/4.5/components/navs/#tabs
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
e.target // newly activated tab
e.relatedTarget // previous active tab
})
You can determine which tab has been selected each time the code fires with e.target.
If you have unique IDs on your elements then you could do something like the following so code only runs when the appropriate tab is clicked.
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
switch (e.target.id){
case "mainTab":{
doMainTabStuff();
break;
}
case "configTab":{
doConfigTabStuff();
break;
}
}
})
<a data-toggle="tab" href="#some_special_tab_anchor">
<div id="some_special_tab_anchor" class="tab-pane fade">
special tab content
</div>
$( 'a[data-toggle="tab"]' ).on( 'shown.bs.tab', function( evt ) {
var anchor = $( evt.target ).attr( 'href' );
alert("TAB SHOWN = "+anchor);
// take action based on what tab was shown
if(anchor === "some_special_tab_anchor"){
// do my special thing :)
}
});
Use my Nuget package for lazyloading bootstrap tabs here, its very simple,
just add "lazyload" class to the "ul" element of bootstrap tabs, then add "data-url" equal to url to load to the any tabs anchor element (a). thats it.
https://www.nuget.org/packages/MT.BootstrapTabsLazyLoader.js/
'show' and 'shown' events didn't work for me. My solution is not exactly specifically OP's situation, but the general concepts are there.
I had the same issue with bootstrap forcing its own onclick events
on tabs (menu buttons and content panels). I wanted to lazy load stuff into a panel depending on what menu button was clicked, and some buttons show a panel on the current page, others were to load a page into an iframe.
At first, I stuffed data into a hidden form field tag, which was the same issue. The trick is to detect some sort of change and act on that. I solved the problem by forcing a change and using an alternate event listening on the buttons without having to touch bootstrap.
1) stash iframe target in button as data attribute:
$('#btn_for_iframe').attr('data-url',iframeurl);
2) bind alternate event onto fire off thingy,
and inside, swap out the iframe source
$('#btn_for_iframe').on('mouseup',function(){
console.log(this+' was activated');
$('#iframe').attr('src',$('#btn_for_iframe').attr('data-url'));
});
3) force 'change' event on panel shows, then load iframe src
$('#iframe_panel_wrapper').show().trigger('change');
or you can put the change trigger in the mouseup above.
$(document).ready(function(){
$(".nav-tabs a").click(function(){
$(this).tab('show');
});
$('.nav-tabs a').on('shown.bs.tab', function(event){
alert('tab shown');
});
});

Binding click function to dynamic divs

There will be number of such div created with unique div id,
when i click on click me it should show an alert for that productid,
i am doing it like
<div id="xyz{productid}">
Click Me
</div>
.....
<script type="text/javascript">
var uuid="{productid}"
</script>
<script src="file1.js">
code from file1.js
$(function () {
var d = "#xyz" + uuid;
$(d).click(function () {
alert("Hello" + uuid);
return false;
});
alert(d);
});
So code is also ok,but the basic problem with it is,
since i m doing it on category page where we have number of products,this function is getting bound to last product tile only,
I want it to be bound to that specific div only where it is been called
..............................
got a solution
sorry for late reply,was on weekend holiday, but i solved it by class type of architecture, where we create an object with each tile on page,and at page loading time we initialize all its class vars,so you can get seperate div id and when bind a function to it, can still use the data from its class variables, i m posting my code here so if any one want can use it,
UniqeDiv= new function()
{
var _this = this;
var _divParams = null;
var _uuid=null;
//constructor
new function(){
//$(document).bind("ready", initialize);
//$(window).bind("unload", dispose);
_uuid=pUUID;
initialize();
$('#abcd_'+_uuid).bind("click",showRatingsMe)
dispose();
}
function initialize(){
}
function showRatingsMe(){
alert(_uuid);
}
function dispose(){
_this = _divParams = null
}
}
//In a target file, im including this js file as below
<script type="text/javascript">
var pUUID="${uuid}";
</script>
<script type="text/javascript" src="http://localhost:8080/..../abc.js"></script>
You can use attribute selector with starts with wild card with jQuery on() to bind the click event for dynamically added elements.
$(document).on("click", "[id^=xyz]", function(){
//your code here
alert("Hello"+this.id);
return false;
});
I would add a class to each of your dynamic divs so that they are easier to query. In the following example, I'm using the class dynamic to tag the div's that are added dynamically and should have this click listener applied.
To attach the event, you can use delegated events with jQuery's on() function. Delegated events will fire for current and future elements in the DOM:
$(function() {
var d="#xyz"+uuid;
$(document).on('click', 'div.dynamic', function() {
alert("Hello"+uuid);
return false;
});
});
You can read more about event delegation here.
You can use
$("[id*='divid_']").click(function(){
});
but for this you need to make sure that all div IDs start with "divid_".

Calling a specific function alone in javascript or jquery

i have a piece of code like this.
// HTML file
<div class="box" ng-click="displayinfo()">
click here to display info about this page.
<div class="content" ng-click="displaytext()">
Click here to display text.
</div>
click here to display info about this page.
</div>
// JS file
$scope.displayinfo = function()
{
alert('info');
}
$scope.displaytext = function()
{
alert('Text');
}
the thing is while clicking on 'click here to display text', it is calling both functions and displaying 'Text' and 'info'. but i dnt want to display 'info' here. i cannot change the html div structure.
how to do that?
It's a little hidden in the docs, but if you look here: http://docs.angularjs.org/api/ng.directive:ngClick
You can see that parameters it mentions an $event object. So your html will become:
<div class="box" ng-click="displayinfo($event)">
click here to display info about this page.
<div class="content" ng-click="displaytext($event)">
Click here to display text.
</div>
click here to display info about this page.
</div>
and then your javascript will become:
$scope.displayinfo = function($event)
{
$event.stopPropagation();
alert('info');
}
$scope.displaytext = function($event)
{
$event.stopPropagation();
alert('Text');
}
jsfiddle: http://jsfiddle.net/rtCP3/32/
Instead calling functions there inline use jquery to solve this issue:
$('.box').click(function(){
displayinfo();
});
$('.content').click(function(e){
e.stopPropagation(); //<-------------------this will stop the bubbling
displaytext();
});
demo code for e.stopPropagation(): http://jsfiddle.net/HpZMA/
var a = "text for info";
$('.box').click(function(){
$(this).append(a)
});
var b = "text for info";
$('.content').click(function(e){
e.stopPropagation(); //<-------------------this will stop the bubbling
$(this).append(b)
});
For native javascript solution you need to pass event as argument to your 2 methods in order to prevent the event from propagating
<div class="box" onclick="displayinfo(event)">
Then change js to:
var displayinfo = function(event) {
event.cancelBubble = true
alert('info')
}
var displaytext = function(event) {
event.cancelBubble = true
alert('text')
}
DEMO: http://jsfiddle.net/MvgTd/
whatever you are getting.stopPropagation();
in your case
$event.stopPropagation();

Categories