multiple bootstrap popovers with unique ids- not working on shown event - javascript

I am trying to create and initialize multiple popovers, using the same code. The html element is being created in JS-
var panel = ('<a href="javascript://" id= "'+popId+'" data-title="xyz" >');
popId is a unique value for each so the ids getting assigned are unique
Next I am calling the following function-
createPopOver("#"+popId,<another_arg>);
The create function looks like this-
function createPopOver(selector,<another_arg>) {
$(selector).popover({
trigger: 'click',
placement : 'left'
}).on('shown.bs.popover', function () {
console.log("reached here1"+selector);
...
});
}
debugging through the control goes to the function however not inside the shown event and so the console does not print anything.
If I give an id="xyz" so now all the popovers have the same id, the very first popover will show up on clicking but with incorrect text (the content to display is being computed in the create popover function).

Be careful when you create your popovers and when you initialize them.
function createPopOver(selector,another_arg) {
console.log(selector);
//$(selector).popover();
$('[data-toggle="popover"]').popover({
}).on('shown.bs.popover', function () {
console.log("reached here1"+selector);
});
}
$(document).ready(function(){
var panel = $('<p><a href="javascript://" id= "123" data-toggle="popover" title="Popover title" data-content="And here\'s some amazing content. It\'s very engaging. Right?" >123</a></p>');
$('body').append(panel);
panel = $('<p><a href="javascript://" id= "234" data-toggle="popover" title="Popover title 234" data-content="And here\'s some amazing content. It\'s very engaging. Right? 234" >234</a></p>');
$('body').append(panel);
panel = $('<p><a href="javascript://" id= "345" data-title="xyz" >345</a></p>');
$('body').append(panel);
panel = $('<p><a href="javascript://" id= "456" data-title="xyz" >456</a></p>');
$('body').append(panel);
createPopOver("#123",'');
createPopOver("#234",'');
createPopOver("#456",'');
});
https://jsfiddle.net/v761q32b/

First of all, I have a strong feeling that you are initializing popover by calling createPopOver function, before you attach elements to DOM, which ain't gonna work. Because event's can be attached to the elements only when it gets attached to the DOM. Alongside, id isn't necessary to attach popover. You can make use of class which can be given to multiple elements, or you can make use of rel or data-* attributes.
var panel = ('<a href="javascript://" id= "'+popId+'" rel="popover" data-title="xyz" >');
Now you can write createPopOver function without the selector argument and popover has selector option where you can specify the selector and attach the popover to body.
function createPopOver(<another_arg>) {
$('body').popover({
trigger: 'click',
placement : 'left',
container: 'body',
selector: '[rel="popover"]', //considering rel as common attribute here
}).on('shown.bs.popover', function () {
console.log("reached here1"+$(this).attr('id'));
...
});
}
You can call createPopOver once your contents of panel variable gets attached to the DOM.
There are various other ways to work on with. Do refer this answer for a detailed explanation on other options.

Related

Remove Class when current toggle is clicked

The title is a bit of a tongue twister. A brief description of the fiddle, is that it's a toggle style accordion where the toggle state changes color when one of the divs is toggled. I've got it working to where if another div is toggled it will close that previous div and open the new div while changing the toggle state.
The issue I am running into is if a user wants to close the current toggle without clicking a different div it will close the current toggle but not change the toggle state back to it's original state. I am currently using this and have tried multiple things including if the container 'is: visible' or hasClass then to remove the toggle class, but nothing seems to work. I've also tried a different slideToggle function, but of course that applied it to the toggled element I've found.
Fiddle: http://jsfiddle.net/NFTFw/1256/
What I am trying to do?
I want the current toggle class to change back to its original state if the user clicks the current toggled div or clicks another div. So essentially I want the user to have either option.
CODE:
$(document).ready(function () {
$('.column').each(function (index) {
$(this).delay(750 * index).fadeIn(1500);
});
$('.column').hide();
$('.body').hide();
$('.column').each(function () {
var $toggle = $(this);
$('.toggle', $toggle).click(function () {
$(".toggle").removeClass("toggle-d");
$(this).addClass('toggle-d');
$body = $('.body', $toggle);
$body.slideToggle();
$('.body').not($body).hide();
});
});
});
Check to see if the thing that you're clicking already has the class. If so, remove it, if not, add it. I suspect the problem you were having with hasClass() is that you were attempting to check the wrong this.
Oooh I did a bad thing and didn't remove the class when a new div was clicked. I've fixed that and updated the jsfiddle
jsfiddle
js:
$(document).ready(function () {
$('.column').each(function (index) {
$(this).delay(750 * index).fadeIn(1500);
});
$('.column').hide();
var width = $(window).width();
if (width <= 600) {
$('.body').hide();
$('.column').each(function () {
var $toggle = $(this);
$('.toggle', $toggle).click(function () {
if($(this).hasClass('toggle-d')){
$(this).removeClass("toggle-d");
}
else{
$('.toggle').removeClass('toggle-d');
$(this).addClass('toggle-d');
}
$body = $('.body', $toggle);
$body.slideToggle();
$('.body').not($body).hide();
});
});
}
});
What i would suggest is to pass the element itself in the function
in the index.html Do this
<a class = 'classname' onclick = toggle(this)>
Your Content Here
</a>
After that in the script.js
what i am saying is in javascript, i believe you can easily convert it to jquery
function toggle(value){
if(value.className == 'the predefined value'){
value.className = value.className + ' Your new class addition'
// remember there should be a space if you are adding an additional class to the present class, else directly change the classname
}
else{
value.className = 'the predefined value'
}}
this will toggle your classname whenever the element is clicked

Removing div's appended using jQuery append()

Hi i have a button which add's a div to my html using jquery append(). Now each of the div's appended has a close button which removes the appended div using jquery remove(). The code looks like this:
$(document).ready(function(){
$("#image-btn").click(function(){
var $imageElement = $("<div class='image_element' id='image-element'><div class='image_holder' align='center'><input type='image' src='{{URL::asset('images/close-icon.png')}}' name='closeStory' class='closebtn' id='close-img-btn' width='22px'><button type='button' class='img_btn' id='img-btn'>Upload Image</button></div></div>");
$("#element-holder").append($imageElement);
$imageElement.fadeIn(1000);
$("#close-img-btn").click(function(){
$imageElement.remove();
});
});
});
Now the problem is arises while removing the appended div's. When i add multiple div's (Each has a close button) and click on the close button of the last appended div nothing happens. But clicking on the close button of the first appended div closes all the other appended div.
I am trying to close only the div that i hit close and not the others. How do i do this ? Would really appreciate if someone could guide me through. Thanks.
ID of an element must be unique, when you use id selector it will return only the first element with the id, so all the click handlers are added to the first button.
Use classes and event delegation
$(document).ready(function () {
$("#image-btn").click(function () {
var $imageElement = $("<div class='image_element' ><div class='image_holder' align='center'><input type='image' src='{{URL::asset('images/close-icon.png')}}' name='closeStory' class='closebtn' width='22px'><button type='button' class='img_btn' >Upload Image</button></div></div>");
$("#element-holder").append($imageElement);
$imageElement.fadeIn(1000);
});
$("#element-holder").on('click', '.closebtn', function(){
$(this).closest('.image_element').remove();
})
});
Demo: Fiddle
More Read:
Event binding on dynamically created elements?
You need remove the parent/child near at button you press.
For example:
$("#close-img-btn").click(function(){
$(this).parent('content-div').remove();
});
use $(this) instead of $imageElement
$(document).ready(function(){
$("#image-btn").click(function(){
var $imageElement = $("<div class='image_element' id='image-element'><div class='image_holder' align='center'><input type='image' src='{{URL::asset('images/close-icon.png')}}' name='closeStory' class='closebtn' id='close-img-btn' width='22px'><button type='button' class='img_btn' id='img-btn'>Upload Image</button></div></div>");
$("#element-holder").append($imageElement);
$imageElement.fadeIn(1000);
$("#close-img-btn").click(function(){
$(this).remove();
});
});
});

jQuery html onclick storing anchor ID, then pulling content from a javascript array

I'm trying to create a html anchor that has a unique ID and then when a user clicks the anchor, the ID gets passed to javascript via the onclick html tag and then a javascript script reads the ID and displays the content in a div. We're using jQuery library for this.
what I have so far:
<a id="MyID1" onclick="var ClickVariable=this.id;return false">1</a>
<a id="MyID2" onclick="var ClickVariable=this.id;return false">2</a>
<script>
var ClickVariable;
var ContentBox = [];
ContentBox[ClickVariable] = "Content for MyID1";
$(ClickVariable).click(function() {
$('.dropdown-menu-content').html(ContentBox);
});
</script>
The above does not work however we have an alternative that works but is not efficient.
<a id="MyID1">1</a>
<a id="MyID2">2</a>
$('#MyID1').click(function() {
$('.dropdown-menu-content').html('Text 1');
});
$('#MyID2').click(function() {
$('.dropdown-menu-content').html('Text 2');
});
As you can see the above one would work but is very repetitive for our needs because we have a large list to enter.
Here is a jsfiddle of the working one that is a tedious repetitive task:
http://jsfiddle.net/2z7o5hn3/
You can reuse the same handler like so:
//mapping id to string to display
var data = {
'MyID1': 'Text 1',
'MyID2': 'Text 2'
}
//shared click handler
var displayEl = $('.dropdown-menu-content');
function handler() {
displayEl.html(data[this.id]);
}
//add click handler to each id
$.each(data, function(k,v) {
$('#'+k).click(handler);
});
http://jsfiddle.net/2z7o5hn3/2/
Give all anchor tags a class and access it like this:
HTML:
<a id="ID1" class="clickVariables" href="#">ID1</a>
<a id="ID2" class="clickVariables" href="#">ID2</a>
JS:
$('.clickVariables').on('click', function(e){
e.preventDefault();
$('.dropdown-menu-content').html($(this).attr('id'));
})
do you mean like this? => DEMO
var texts=['Text 1','Text2'];
$('a[id^=MyID]').click(function() {
$('.dropdown-menu-content').html(texts[$(this).text()-1]);
});

Alternative writing method to create DOM elements and append

If I want to append a button with my pic to the document, I would write:
$('#story_pages').append('<div><button value="'+window_value+'" onclick="reload_to_canvas(this.value)" > <img id= "w'+window_value+'", src="../pic/white_img.png", width="110px", height="110px"/> </button></div>');
It's too long and hard to debug. But how can I create an img tag, then wrapping it with a button tag and div tag...
Please suggest any clear and simple method with jQuery's help.
UPDATE:
story_pages is the jQuery UI dialog's id. I don't know if it affects or not.
UPDATE:
I found the problem. I want the image shown above on the button instead of a button and a image.
The script you give me will result this:
<div>
<button value="1"></button>
<img ......./>
</div>
The img tag has to be wrapped by button tag like:
<button>
<img.../>
</button>
So the image will attach on the button.
How about this:
var $button = $('<button>', {
value: window_value,
click: function() { reload_to_canvas(this.value); }
});
var $img = $('<img>', {
id : 'w'+ window_value,
src: '../pic/white_img.png'
})
.css({ height: '100px', width: '100px'});
$('#story_pages').append($('<div>').append($button, $img));
If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML (i.e., it starts with ). If not, the string is interpreted as a selector expression, as explained above. But if the string appears to be an HTML snippet, jQuery attempts to create new DOM elements as described by the HTML. Then a jQuery object is created and returned that refers to these elements.
try this
var div=$('<div>'); // creates new div element
//updated here
var img = $('<img />') .attr({ // create new img elementand adds the mentioned attr
id:'w'+window_value ,
src:"../pic/white_img.png",
width:"110px",
height:"110px"});
var button= $('<button/>', //creates new button
{
value: window_value, //add text to button
click: function(){ reload_to_canvas(this.value)} //and the click event
}).html(img); /// and <-- here... pushed the created img to buttons html
div.append(button); //append button ,img to div
$('#story_pages').append(div); //finally appends div to the selector
updated example fiddle
$('#story_pages').append(
$('<div>').append(
$('<button>', {
value : window_value
}).click(function() {
reload_to_canvas(this.value);
}).append(
$('<img>', {
id : 'w' + window_value,
src : '../pic/white_img.png'
}).width(110)
.height(110)
)
)
);

Remove hover and default state from jquery ui button

I have a set of anchors that I am converting to buttons like so:
var sideMenuAnchors = $("#divLeft a");
sideMenuAnchors.width("120px");
sideMenuAnchors.button();
However when one of these anchors is clicked I want the ui-state-active to remain until another button is clicked ... I have been unable to find a simple solution, is there one ?
I have tried this:
$('#anchor01').unbind('onmouseover').unbind('onmouseout');
and this :
$('#anchor01').disable()
However neither do what I require, as the ui-active-state is still removed on mouseout
Edit
The solution I implemented was to manually add the button classes that I required from jquery-ui, like so:
var sideMenuAnchors = $("#divLeft a");
sideMenuAnchors.addClass("ui-state-default ui-button ui-button-text-only");
sideMenuAnchors.width("120px");
sideMenuAnchors.height("25px");
sideMenuAnchors.removeClass('ui-corner-all');
sideMenuAnchors.first().addClass('ui-corner-top');
sideMenuAnchors.last().addClass('ui-corner-bottom');
sideMenuAnchors.hover( function() {
$(this).addClass("ui-state-hover");
},function() {
$(this).removeClass("ui-state-hover");
});
Since you're transforming hyperlinks into jQuery UI buttons, there are no group relationship between them and they're all considered as independent.
However, if you were transforming radio buttons (with the same name attribute), then jQuery UI would maintain the group relationship and you would obtain the behavior you're aiming for.
So, you can do just that: first, add a radio button and its associated label to each hyperlink, then transform these into buttons:
<form>
<div id="divLeft">
<a id="link1" href="#">Foo</a>
<a id="link2" href="#">Bar</a>
<a id="link3" href="#">Quux</a>
</div>
</form>
$(document).ready(function() {
$("#divLeft a").each(function() {
var $this = $(this);
var text = $this.text();
var radioId = $this.attr("id") + "_radio";
$this.text("").append(
$("<input type='radio' name='buttons'>").attr("id", radioId),
$("<label>").attr("for", radioId).text(text));
});
$("#divLeft a input:radio").width("120px").button();
});
You can see the results in this fiddle.

Categories