I have been going through so many posts about this but I can't find anything that works for me.
I'm trying to refresh ONLY A div section NO PHP files. The languages that I'm coding in are Javascript, jQuery, Bootstrap, and CSS.
This is the section I want to refresh
https://stackoverflow.com/a/58207615/5413196
Yes, it's my post I just don't want to recreate the same info again...
Because there is a Split function in an array of images that if you click on it the first image goes behind all of them.
Example array = [1,2,3,4] User clicks [2,3,4,1] but the DOM request is only loaded once on that section and after the user clicks the second click doesn't return the 2nd image behind [3,4,1,2]
I Understand that a DOM is only loaded once but I would really like it if I can find a way with Javascript or jQuery to refresh the div on click or auto-refresh after X seconds so that the user can click on an image again...
Provide background including what you've already tried
Scowered the whole StackOverflow for answers
Some refresh code I tried
Refresh DIV With Javascript Button
Refresh only one div with AJAX
div refresh without click of the button
Refresh div without load
refresh only one div
Onclick refresh only div
Any assistance would be amazing
Thanks in advance
Faz
EDIT
I was asked to add the code from the other post.
let image_arr = [{
id: 'part_1',
image_src: 'http://placeimg.com/100/100/animals?t=1570040444517',
h6_tag: 'Bradley Hunter',
p_tag: 'Based in Chicago. I love playing tennis and loud music.',
pin: 'a',
},
{
id: 'part_2',
image_src: 'http://placeimg.com/100/100/animals?t=1570040444516',
h6_tag: 'Marie Bennet',
p_tag: 'Currently living in Colorado. Lover of art, languages and travelling.',
pin: 'b',
},
{
id: 'part_3',
image_src: 'http://placeimg.com/100/100/animals?t=1570040444515',
h6_tag: 'Diana Wells',
p_tag: 'Living in Athens, Greece. I love black and white classics, chillout music green tea.',
pin: 'c',
},
{
id: 'part_4',
image_src: 'http://placeimg.com/100/100/animals?t=1570040444514',
h6_tag: 'Christopher Pierce',
p_tag: 'Star Wars fanatic. I have a persistent enthusiasm to create new things.',
pin: 'd',
},
];
$(document).ready(function () {
// create
createPartnerRow(image_arr);
// set image background
})
$(document).ready(function () {
$("[id^=part_]").hover(function (image_arr) {
$(this).addClass('border')
},
function () {
});
});
$("[id^=part_]").ready(function () {
$("[id^=part_]").click(function () {
$(this).removeClass('border')
// set value
var current_partner = image_arr[0];
// remove first element from array
image_arr = image_arr.splice(1, 4);
// append current_partner to end of array
image_arr.push(current_partner);
// clear the row of all partners;
$('#part_1, #part_2, #part_3, #part_4').remove();
// recreate row
console.log(image_arr);
createPartnerRow(image_arr);
});
})
function createPartnerRow(image_arr) {
for (i = 0; i < image_arr.length; i++) {
$('#partner_row').append(
'<div class="col-md-3 col-sm-6 p-3" id="' + image_arr[i].id + '">' +
'<button class="border-0 bg-white">' +
'<div class="facebox"><img class="rounded-circle img-fluid mx-auto d-block" src="' + image_arr[i].image_src + '"' + '/><span class="pin">' + image_arr[i].pin + '</span></div>' +
'<h6 class="text-center g-mt-50 font-weight-bold pt-2">' + image_arr[i].h6_tag + '</h6>' +
'<p class="text-center g-mt-50 pt-2">' + image_arr[i].p_tag + '</p>' +
'</button>' +
'</div>'
)
}
}
#partner_row {display:flex;}
.bg-white {background: transparent;}
.facebox{
position:relative;
display:inline-block; margin:auto;
width:80px; font-size:0;
}
.facebox .rounded-circle{
width:100%; border-radius:50%;
}
.facebox .pin {
display:block;
width:22px;
height:22px;
border:3px solid white;
border-radius:50%;
background:blue;
position:absolute;
bottom:-3px;
right:-3px;
color:white; text-align:center; font-size:13px; line-height:20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row" id="partner_row"></div>
well if you want to be amazed with a nice DOM system, try React...but...for what you're looking for: have you tried changing the innerHTML.
-so you target the element with an onclick function (addEventListener in JS or add onclick in the HTML)
-then you give your div an id like <div id="myDiv"></div>
-then in the onclick target fucntion/event listener target function you use :
document.getElementById("myDiv").innerHTML =
`<div>` +
` <p>write whatever html you want in here</P>` +
`</div>`;
you dont need to reload the whole DOM, just change the innerHTML of the element you want. there are a few ways to do this, but i think this might be the best bet for you. let me know how it works.
As written, the '#part_1, #part_2, #part_3, #part_4 elements (along with their hover and click event handlers) are destroyed then re-rendered on every rotation.
Hence second and subsequent clicks don't work.
There's a number of ways to cope with this:
Reattach event handlers after re-rendering.
Delegate event handling to the static container, #partner_row.
Render #partner_row once then rotate the images non-destructively by DOM manipulation, ensuring that the event handlers remain attached.
Approach 3 will has an additional advantage of being far more efficient than rotating the array and re-rendering from scratch. Here it is in full:
$(function () {
var $partnerRow = $('#partner_row');
// Render partners as a side effect of mapping image_arr to an array of jQuery objects,
// then wrap to make a jQuery set.
$(image_arr.map(function(imgData) {
$('<div class="col-md-3 col-sm-6 p-3" id="' + imgData.id + '">' +
'<button class="border-0 bg-white">' +
'<div class="facebox"><img class="rounded-circle img-fluid mx-auto d-block" src="' + imgData.image_src + '"' + '/><span class="pin">' + imgData.pin + '</span></div>' +
'<h6 class="text-center g-mt-50 font-weight-bold pt-2">' + imgData.h6_tag + '</h6>' +
'<p class="text-center g-mt-50 pt-2">' + imgData.p_tag + '</p>' +
'</button>' +
'</div>').appendTo($partnerRow);
}))
.hover(function() { // permanently attach event handlers to the rendered elements
$(this).addClass('border');
}, function () {
// $(this).removeClass('border'); // ???
}).on('click', function () {
$(this).removeClass('border');
// rotate images non-destructively by DOM manipulation
$partnerRow.find('.col-md-3.col-sm-6.p-3').eq(0).appendTo($partnerRow); // selector may simplify.
});
});
Related
This question already has answers here:
How to change content of div on hover using JQuery/Javascript
(6 answers)
Closed 3 years ago.
I have a link inside a div. Inside the link (between the ), I have text displayed. I want to change that text when the cursor hovers over the link.
***One thing I forgot to mention is that I want the text to be temporarily changed (i.e. only when it's hovered over).
Here's my JSFiddle: https://jsfiddle.net/ZEZEME/kapt4sL6/5/
This is what my code looks like.
HTML
<div id="imgDiv"></div>
CSS
#imgDiv {
width: 200px;
height:200px;
background-color: gray;
}
JS
var title = "World War II Plane Crashes in National Parks";
var url = "https://www.nps.gov/articles/WWIIPlaneCrashes.htm"
$(imgDiv).append($('<a href="' + url + '" id=link>'+ title +'</a>'));
(I'm working with APIs, and .append is how I create the links. I need to dynamically create them to the div in JavaScript).
This is what I've tried:
$(imgDiv).append($('<a href="' + url + '" id=link>'+ title +'</a>').css('text-decoration', 'none').hover(function(e) {
console.log($(e.target).text("NEWWW"));
}));
This permanently changes the text (as opposed to only when hovered over).
$(imgDiv).append($('<a href="' + url + '" id=link>'+ title +'</a>').css('text-decoration', 'none').hover(function(e) {
function(e) {
console.log($(e.target).text("NEWWW"));
},
function(e) {
console.log($(e.target).text("OLDDD"));
}
This gives me an error. Can anyone help?
You can use mouseover to detect when the mouse moves over the link, you can then use mouseout to see when it leaves the link.
You also want to use text() as val() is for form fields.
var title = "World War II Plane Crashes in National Parks";
var url = "https://www.nps.gov/articles/WWIIPlaneCrashes.htm"
$('#imgDiv').append($('<a href="' + url + '" id=link>'+ title +'</a>'))
// Create an event to watch "a" tags
$('#imgDiv a').on('mouseover', (e) => {
$(e.target).text('I am some new text')
})
// Comment this out if you don't want it to go back on mouse out.
.on('mouseout', (e) => {
$(e.target).text(title)
});
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#imgDiv {
width: 200px;
height:200px;
background-color: gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="imgDiv"></div>
I am using fabricjs to load image and textcontents.
I have many textcontents on canvas with fabricjs.
now on click of textcontents of fabricjs I want to open Angular 7 popover may be (ngbPopover).
how to open that on click of textcontents, like we are opening dialogbox?
because I can not inject popover config anywhere in fabricjs.
I had similar functionality to do but I found another shortcut way in doing it so.
On click of the text, object read the object by using
this.canvas.on('object:selected', (e) => {this.objectSelected(e)});
Then initally makesure that the textbox/popover is hidden
On click of the object read the selected object by:
var absCoords = this.canvas.getActiveObject();
When you read the active object there are things that you will have to take care
unhide the textbox/popover
get absCoords.left and absCoords.top and set it to the textbox.
This is one of the workarounds which helped to solve it.
Actually I was trying to say something like this, And I found solution here.
const showImageTools = (e) => {
const content = '<div id="imageDialog" class="container">\n' +
' <mat-form-field class="example-full-width">\n' +
' <input value="' + pngText.texts + '" id="textInputField" style="width: 400px;\n' +
' box-shadow: 2px 4px 5px 3px #bdc3bdee;height: 50px;\n' +
' padding: 5px;\n' +
' border-radius: 5px;" matInput placeholder="Add your texts"/>\n' +
' </mat-form-field>\n' +
' </div>';
$("body").append(content);
moveImageTools();
};
this.canvas.add(pngText).renderAll();
pngText.on('mousedown', event => {
showImageTools(event);
});
On my webpage there are Gridster widgets.In these widgets initially the images are displayed from JSON(the name of image comes from JSON which I then put in src of image)
The users can also add images by clicking + button.User can also delete an image by clicking X button on the image.
The Problem I am facing
When the images coming from JSON are more or when the user manually adds more images then the images go out of widgets.
My Desired Output
Now I was trying to restrict those images in widget such that images will lay only in boundaries of div.
When there are more images the other existing images will resize and all of the images will fit in that area.
When I delete an image the other images will get bigger.In any case the entire area will be occupied by the images.
JS:
//JSON which I get from backend
var json = [{
"html": "https://d30y9cdsu7xlg0.cloudfront.net/png/802768-200.png,https://d30y9cdsu7xlg0.cloudfront.net/png/802768-200.png,https://d30y9cdsu7xlg0.cloudfront.net/png/802768-200.png", //3 Images
"col": 1,
"row": 1,
"size_y": 2,
"size_x": 2
}
];
//Loop which runs over JSON to generate <li> elements in HTML
for (var index = 0; index < json.length; index++) {
var images = json[index].html.split(',');
var imageOutput = "";
for (var j = 0; j < images.length; j++) {
imageOutput += '<div class="imagewrap"><img src=' + images[j] + '> <input type="button" class="removediv" value="X" /></div></div>';
}
gridster.add_widget('<li class="new" ><button class="addmorebrands" style="float: left;">+</button><button class="delete-widget-button" style="float: right;">-</button>' + imageOutput + '<textarea>' + json[index].html + '</textarea></li>', json[index].size_x, json[index].size_y, json[index].col, json[index].row);
}
//Function to delete an image from widget
$(document).on('click', '.removediv', function() {
$(this).closest('div.imagewrap').siblings('textarea')
$(this).closest('div.imagewrap').remove();
});
//Function to delete a widget
$(document).on("click", ".delete-widget-button", function() {
var gridster = $(".gridster ul").gridster().data('gridster');
gridster.remove_widget($(this).parent());
});
//Function to add mode Images to widgets from Modal
var parentLI;
$(document).on("click", ".addmorebrands", function() {
parentLI = $(this).closest('li');
$('#exampleModalCenter').modal('show');
$('#exampleModalCenter img').click(function() {
$(this).addClass('preselect');
$(this).siblings().removeClass('preselect');
selectedImageSRC = $(this).attr('src');
})
});
$('#add-image').click(function() {
parentLI.append('<div class="imagewrap"><img src="' + selectedImageSRC + '"> <input type="button" class="removediv" value="X" /></div>');
parentLI.children('textarea').append(', ' + selectedImageSRC);
$('#exampleModalCenter').modal('hide');
})
HTML
<div class="gridster">
<!-- <li> from JSON are placed here images are a part of li -->
<ul>
</ul>
</div>
The Fiddle so far
I am not sure if this can achieved just with CSS or will require any JS along with that
Update 1
I have tried with a lot of different CSS but still not able to get the expected output so if someone can help me with it would be really helpful
Maybe Gridster has a built in way to arrange items inside the grid cells, in case you have not found a way yet, try this.
I added some css:
.image-wrap-container{
min-height: 70%
}
.image-wrap-container div.imagewrap{
width: 33%
}
.text-area-wrap{
bottom: 0px;
left: 0px;
margin: 0px;
padding: 0px;
width: 100%;
height: 30%;
display: inline-flex;
}
.new.gs-w{
width: 200px;
min-height: 200px
}
.addmorebrands{
position: absolute;
left:0
}
.delete-widget-button{
position: absolute;
right:0
}
and restructured a little bit your html so images fit good within the cell, I hope that does not break anything, javascript was the least modified, only to add the images according to the new html structure.
Note: I tried to make the lis' height adjust to the amount of elements it contains, but [data-sizey="2"] kept getting in my way, so before throwing some probably unnecessary hack on it, try and achieve that using the library's own options, good luck.
Also, I noticed you were using this to update your textareas:
parentLI.children('.imagenames').val(function(i, selectedImageSRC) {return selectedImageSRC + ', '});
which won't work because you are using the same name for the argument, conflicting with the original selectedImageSRC variable. In case you are still having problems in that front, I replaced it with:
parentLI.children('.imagenames').val(function(i, currentContent) {return currentContent + ',' + selectedImageSRC + ', '});
Bonus Feature
The buttons for removing an image were to big for the images and covered quite a big part, so I took the liberty:
.removediv{
visibility: hidden
}
.imagewrap:hover .removediv{
visibility: visible
}
hope it helps
I'm trying to write a JavaScript widget in object-oriented JavaScript, or at least what I understand JS' near-equivalent of classes to be.
All I'm trying to achieve is a menu which changes state. In pseudo;
Upon widget load, populate #nav with a <ul> menu containing year group <li>s.
Upon clicking a year group <li>, empty #nav ul of its <li> and re-populate it with tutor group <li>s in that year, as well as appending a return link.
Upon clicking the return link, empty #nav and re-populate it with the original year group <ul> menu whilst being able to utilise all of the above functionality.
Historically, i.e. to date, I've used "embedded" functions to try and keep everything within the same DOM layer/timing. I don't really understand how any of this works, or if this is an appropriate thing to do, but the code itself seemed to work.
Here's an example of the way I've done it previously:
var GroupsDisplayHTML = '<h2>Tutor Groups</h2>' +
'<ul><li><a class="year" href="javascript:void(0);" title="Year 9" id="9">Year 9</a></li>' +
'<li><a class="year" href="javascript:void(0);" title="Year 10" id="10">Year 10</a></li>' +
'<li><a class="year" href="javascript:void(0);" title="Year 11" id="11">Year 11</a></li>' +
'<li><a class="year" href="javascript:void(0);" title="Year 12" id="12">Year 12</a></li>' +
'<li><a class="year" href="javascript:void(0);" title="Year 13" id="13">Year 13</a></li></ul>';
$("div#groups").html(GroupsDisplayHTML);
$('a.year').click( function() {
var Groups;
var Groups_Sorted = [];
Frog.API.get('groups.getAll',
{
'onSuccess': function (data) { Groups = data; },
'onError': function(err) { alert(err); }
});
for (var i = 0; i < Groups.length; i++) {
var Year = $(this).attr("id");
if (Groups[i].name.indexOf(Year) == 0 && Groups[i].name.indexOf('/Tp') != -1) {
var arrayToPush = { 'id': Groups[i].id, 'name': Groups[i].name };
Groups_Sorted.push(arrayToPush);
}
}
GroupsDisplayHTML = '<h2>Year ' + Year + '</h2><ul>';
for(var i = 0; i < Groups_Sorted.length; i++){
GroupsDisplayHTML += '<li><a class="group" href="javascript:void(0);" title="' + Groups_Sorted[i].id + '" id="' + Groups_Sorted[i].id + '">' +
Groups_Sorted[i].name + ' <span style="font-size:10px;color:#bbb;">(' + Groups_Sorted[i].name + ')</span></a></li>';
}
GroupsDisplayHTML += '<li><a class="return" href="javascript:void(0);"><- Back to Year Groups</a></li></ul>';
$("div#groups").html(GroupsDisplayHTML);
$('a.group').click( function() {
var Group_ID = $(this).attr("id");
AssignPoints.getUsers(Group_ID);
});
$('a.return').click( function() {
AssignPoints.displayGroups(data);
});
});
However, now, I'm wondering if the better way to do it is to use jQuery's on function. Here's the code I'm currently writing (*just to try and achieve the changing-state menu):
var TutorGroupPoints = {
URL: 'http://staff.curriculum.local/frog/rewards.php',
currentUser: UWA.Environment.user.id,
groupsObject: { },
sortedArray: [ ],
navHTML: '<h2>Tutor Groups</h2>' +
'<ul>' +
'<li><a class="year" title="Year 9" id="9">Year 9</a></li>' +
'<li><a class="year" title="Year 10" id="10">Year 10</a></li>' +
'<li><a class="year" title="Year 11" id="11">Year 11</a></li>' +
'<li><a class="year" title="Year 12" id="12">Year 12</a></li>' +
'<li><a class="year" title="Year 13" id="13">Year 13</a></li>' +
'</ul>',
init: function() {
/* caching outer this -> AJAX scope problems */
var that = this;
/* retrieve all of the user groups from Frog VLE and store them in an object-level variable */
Frog.API.get('groups.getAll',
{
'onSuccess': function (data) { that.groupsObject = data; },
'onError': function(err) { alert(err); }
});
/* populate the div#nav with our year group UL */
$('#nav').append(this.navHTML);
/* using "on" because the LIs have been created in the DOM? */
$('#nav ul').on("click", "li a", function(e) {
e.preventDefault();
that.yearClick( $(this).attr("id") );
});
},
yearClick: function(year) {
/* run through groupsObject and pull out any tutor groups found in the year we've clicked on
then put those into our sortedArray */
for (var i = 0; i < this.groupsObject.length; i++) {
if (this.groupsObject[i].name.indexOf(year) == 0 && this.groupsObject[i].name.indexOf('/Tp') != -1) {
/* all we need is name and id */
var arrayToPush = { 'id': this.groupsObject[i].id, 'name': this.groupsObject[i].name };
this.sortedArray.push(arrayToPush);
}
}
/* clear the existing UL from div#nav */
$('#nav ul').empty();
/* populate div#nav's UL with LIs of our tutor groups (label being name, attr="id" being id) and
clickable links for each */
for (var i = 0; i < this.sortedArray.length; i++) {
$('#nav ul').append('<li><a class="tutor" id="' + this.sortedArray[i].id + '">' + this.sortedArray[i].name + '</a></li>');
}
/* add a "return" link to view other years' tutor groups */
$('#nav ul').append('<li><a id="return"><- Return</a></li>');
/* upon clicking the return link, empty #nav ul then re-append our navHTML from earlier */
$('#nav ul').on("click", "a#return", function(e) {
e.preventDefault();
$('#nav ul').empty();
$('#nav').append(this.navHTML);
});
/* upon clicking any of our tutor group LIs, display that link's id so that we can use it in
another function to actually display some content */
$('#nav ul').on("click", "a.tutor", function(e) {
e.preventDefault();
alert( $(this).attr("id") );
});
}
};
widget.onLoad = function(){
/* run our "class" */
TutorGroupPoints.init();
}
And the HTML:
<div id="wrapper">
<div id="nav">
</div>
<div id="content">
</div>
</div>
I've created a jsFiddle here, which is a slight manipulation of the code (i.e. I've removed the inaccessible Frog API calls and replaced them with a fixed object). Hopefully this works adequately.
The problem here is that once I click the return button, nothing happens. In addition, I suspect that fixing the return button would then provide me with some links which, when clicked upon, would do nothing.
Ideally, as per the bottom end of the code, I would like to run another function within my TutorGroupPoints class when the user clicks on a specific tutor group. How will this affect my return button, etc? Will they then stop working because they aren't being run from the "current" function?
More than "just" an answer to my code problems, I'd quite like some direction, i.e. is the recent code I've written better than the older stuff? Should I be using on or should I be using embedded jQuery functions and communicative class functions?
Thanks in advance,
Short answer: http://jsfiddle.net/byzgv/4/
I'm not sure about the OOP aspect, but this seems to be your scenario:
when the page is loaded, you insert a list into a div.
you add some event handlers to this list
you click a list item, your event handlers run, and change the list items.
the "Return" list item "does nothing" when you click it.
In your fiddle, clicking the "Return" list item does do something, it empties this list. This is partly what you asked it to do:
$('#nav').on("click", "ul a#return", function(e) {
e.preventDefault();
$('#nav ul').empty();
$('#nav').append(this.navHTML);
});
So this event handler has fired, and the first two instructions have worked. The call to append doesn't work because you're in a different context - this does not refer to the TutorGroupPoints object. So you can fix this by referring to your object explicitly:
$('#nav').on("click", "ul a#return", function(e) {
e.preventDefault();
$('#nav ul').empty();
$('#nav').append(TutorGroupPoints.navHTML);
});
(by the way, you're appending a whole new list, so you need to do $('#nav').empty(); instead of $('#nav ul').empty();)
Then, as you guessed, clicking the "Return" item gives you a new list which doesn't respond to click events. This is because of how you're calling the on function. The jQuery object you call on on must exist when the event handler is being set up. In your init function, the list does exist when you set up the event handlers, as you're appending it to the div before calling on. But later, you trash this list and replace it.
To get your event handlers working on all lists rather than just the first one, you need to attach your event handlers to an element that exists from the start and doesn't change, i.e. the #nav div. So
$('#nav ul').on("click", "li a", function(e) {
can become
$('#nav').on("click", "ul li a", function(e) {
I have an issue where I have nested divs with the same class. For instance I have something like Panel, inside of Panel. However, when I click on the panel inside the first panel, it is the first panel that triggers the
$(".panel").click
function. However, I need to somehow drill down to the panel which the mouse actually clicked on. In other words if I had the following code:
<div class="panel"> //first panel
<div class="panel"> //second panel
</div>
</div>
When I want the second panel to trigger the click, I instead get the parent panel triggering the click. This makes sense given the second panel is wrapped in the first panel. However, I was wondering if there is a way around this? In theory, the code that I am writing can have an infinite ammount of panels inside of other panels. Is there a way to drill all the way down to the panel that the mouse has clicked on? (not the containing panel)
EDIT:
Here is the entire code segment:
<style type="text/css">
body
{
height: 700px;
}
.gridSegment
{
width: 50%;
height: 50%;
float: left;
outline: 2px solid black;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
var lastID = 10;
$(".gridSegment").dblclick(function(){
console.log($(this).attr("ID"));
lastID++;
$(this).append("<div class='gridSegment' id='" + lastID + "'></div>");
lastID++;
$(this).append("<div class='gridSegment' id='" + lastID + "'></div>");
lastID++;
$(this).append("<div class='gridSegment' id='" + lastID + "'></div>");
lastID++;
$(this).append("<div class='gridSegment' id='" + lastID + "'></div>");
return false;
});
});
</script>
</head>
<body>
<div class='gridSegment'>
<div class='gridSegment' id ="1"></div>
<div class='gridSegment' id ="2"></div>
<div class='gridSegment' id ="3"></div>
<div class='gridSegment' id ="4"></div>
</div>
</body>
Check out this example on jsFiddle (open your JavaScript console)
(please excuse the ugly colors - I'm a programmer not a designer ;).
$(function(){
$('.panel').on('click',function(e){
console.log($(this));
return false;
});
});
All you have to do is return false when you capture the click to stop the event bubbling back up to the containing element.
I've taken the liberty of changing your code slightly (just for the example). Mainly the loops and I also changed the id attributes to add a little more information - you can now see exactly what level you are in. If you feel it suites your needs then by all means you can adopt it into your application.
You mentioned in a comment that the .live() function solves your problem, however this feature is deprecated as of jQuery 1.7 and it is recommended to use the delegate() function in place of live() if you can't use on(). So here is my solution using the delegate() function.
As you can see the syntax is similar only that we attach the callback to the container element and specify what internal selector to use - in our case it is any .gridSegment element.
$("#body").delegate(".gridSegment", "dblclick", function() {
var $thisCached = $(this);
console.log($thisCached,$(this).parent());
var lastId = $thisCached.attr("id");
var limit = 4;
var counter = 1;
while(counter <= limit){
var newId = lastId + '_' + counter;
counter++;
$thisCached.append("<div class='gridSegment' id='" + newId + "'></div>");
}
return false;
});
Note that my wrapper is an element with the id of body
jsFiddle example
Use id's
<div class="panel" id="panel_1">
<div class="panel" id="panel_2">
...
or use data-* attributes
<div class=panel data-pid=1>
then
$('.panel').click(function(){
alert('panel id is: '+$(this).attr('data-pid'));
})