Get ID of div created by jquery - javascript

I have two functions, where the first creates a div in the dom and the second gets the ID via getElementById(). Unfortunately, my second function is just returning null.
I looked in using $.Deffered() in either of my functions, but alas nothing I do seems to work
function one() {
var dynamicDiv = $("<div>").attr("id", 'test');
dynamicDiv.iziModal({
//modal content here
})
}
function two() {
var container = document.getElementById('test');
console.log(container.innerHTML); //not returning any data
}
enter code here
I had hoped to use this with a library that replaces images with a canvas object, but it requires that the "parent element to be a valid DOM Element". I have been searching for a while now, but I can not seem to find anything on the subject that is applicable.
** Edit**
Thank you for pointing out the error in my id (I had tried something else before I pasted). The iziModal function (http://izimodal.marcelodolza.com/) is currently pulling the content in via ajax (which I assume is the problem here):
The iziModal Function:
dynamicDiv.iziModal({
title: '',
autoOpen: 1,
width: 500,
onOpening: function (offer) {
offer.startLoading();
$.get(demoUrl, function (data) {
$('#' + id + " .iziModal-content").html(data);
offer.stopLoading();
});
}
});
Content of the other file:
<div id="test">
<img src="./bundle/images/coupon.jpg" />
</div>

function one() {
var dynamicDiv = $("<div>").attr("id", 'test');
dynamicDiv.iziModal({
//modal content here
});
$("body").append(dynamicDiv);
}

Related

Adding a getElementById to an jquery .get function

I need to get from 'page'+i a container div with id = 'posts1', but I'm struggling to add a .getElementById or similar to this function:
$.get('page-'+i, function(data){
content = data;
$('#posts').append(content);
});
I've tried adding it on content, data and putting 'page'+i in brackets and then adding .getElementById but nothing works, i'm always getting that what i'm doing isn't a function or error 500 (Internal Server Error).
Edit:
This is the full function:
function showMore() {
if (i<=196) {
$.get('page-'+i+' #posts' , function(data){
content = data;
$('#posts').append(content);
});
i++;
}
This is activated on a click of a button.
I need to append, after the existing articles in #posts, more articles that are for ex in page-2 in the div with id 'posts1'.
I've found where was my issue:
function showMore() {
if (i<=196) {
$.get('page-'+i , function(data) {
var content = $(data).find('#posts1');
$('#posts').append(content);
});
i++;
}
}
I've added .find to my data and it's working perfectly.
You can use template literals and .load
If i is 1, then this will read a page with filename page-1 and insert the element from that page with id="post1" into the element with id="posts" on current page
$('#posts').load(`page-${i} #post1`)
Added to a simpler version of your function
function showMore() {
if (i>196) return;
$('#posts').load(`page-${i} #posts`);
i++;
}

How do i resolve "Cannot read properties of undefined (reading 'ownerDocument')"

I am trying to add a div inside the main div on page loading, it works when i write the code like this:
function DivAdder() {
$('#mainDiv').append('<div class="newspaper-wrapper"></div>');
}
DivAdder();
window.onload = DivAdder;
But i want to make this function have a parameter so i can just pass its name instead of writing the whole string in .append function. I wrote something like this but i am having the error from the title:
function DivAdder(variable) {
$('#mainDiv').append($(variable));
}
DivAdder('<div class="newspaper_wrapper"></div>');
window.onload = DivAdder;
And i tried this as well:
$('#mainDiv').append(variable);
But nothing happens. I read some documentation but was not successful.
Appreciate the help <3 .
This is because window.onload passes an Event object as first argument. If you console.log(variable), it will tell you it's an Event.
You need to keep this first argument as an optional event, and pass your HTML as second argument :
function DivAdder($event, html) {
console.log("Event = ", $event)
console.log("Adding div : " , html)
$('#mainDiv').append(html);
}
DivAdder(null, '<div class="newspaper_wrapper">TEST</div>');
window.onload = DivAdder; // This will call DivAdder( LoadEvent )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mainDiv"></div>
I'm not sure why you're assigning window.onload = DivAdder in the first place, since this won't add any HTML and won't do anything at all. You can get rid of it completely, it's only causing trouble.
function DivAdder(html) {
console.log("Adding div : " , html)
$('#mainDiv').append(html);
}
DivAdder('<div class="newspaper_wrapper">TEST</div>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mainDiv"></div>

Jquery .change() event fires only once

So I'm fairly novice with jquery and js, so I apologise if this is a stupid error but after researching I can't figure it out.
So I have a list of data loaded initially in a template, one part of which is a dropdown box that lets you filter the data. My issue is that the filtering only works once? As in, the .change function inside $(document).ready() only fires the once.
There are two ways to reload the data, either click the logo and reload it all, or use the search bar. Doing either of these at any time also means the .change function never fires again. Not until you refresh the page.
var list_template, article_template, modal_template;
var current_article = list.heroes[0];
function showTemplate(template, data)
{
var html = template(data);
$("#content").html(html);
}
$(document).ready(function()
{
var source = $("#list-template").html();
list_template = Handlebars.compile(source);
source = $("#article-template").html();
article_template = Handlebars.compile(source);
source = $("#modal-template").html();
modal_template = Handlebars.compile(source);
showTemplate(list_template,list);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = list.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
$("#classFilter").change(function()
{
console.log("WOW!");
var classToFilter = this.value;
var filteredData =
{
heroes: list.heroes.filter(function(d)
{
if (d.heroClass.search(classToFilter) > -1)
{
return true;
}
return false;
})
};
console.log(filteredData);
showTemplate(list_template,filteredData);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = filteredData.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
});
$("#searchbox").keypress(function (e)
{
if(e.which == 13)
{
var rawSearchText = $('#searchbox').val();
var search_text = rawSearchText.toLowerCase();
var filteredData =
{
heroes: list.heroes.filter(function(d)
{
if (d.name.search(search_text) > -1)
{
return true;
}
return false;
})
};
console.log(filteredData);
showTemplate(list_template,filteredData);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = filteredData.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
}
});
$("#logo").click(function()
{
showTemplate(list_template,list);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = list.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
});
//$("#logo").click();
});
function displayModal(event)
{
var imageNumber = $(this).data("id");
console.log(imageNumber);
var html = modal_template(current_article.article[0].vicPose[imageNumber]);
$('#modal-container').html(html);
$("#imageModal").modal('show');
}
I should note two things: first, that the search bar works perfectly, and the anonymous function inside both of them is nearly identical, and like I said, the filtering works perfectly if you try it after the initial load. The second is that the same problem occurs replacing .change(anonymous function) with .on("change",anonymous function)
Any help or advice would be greatly appreciated. Thanks.
I agree with Fernando Urban's answer, but it doesn't actually explain what's going on.
You've created a handler attached to an HTML element (id="classFilter") which causes part of the HTML to be rewritten. I suspect that the handler overwrites the HTML which contains the element with the handler on it. So after this the user is clicking on a new HTML element, which looks like the old one but doesn't have a handler.
There are two ways round this. You could add code inside the handler which adds the handler to the new element which has just been created. In this case, that would mean making the handler a named function which refers to itself. Or (the easier way) you could do what Fernando did. If you do this, the event handler is attached to the body, but it only responds to clicks on the #classFilter element inside the body. In other words, when the user clicks anywhere on the body, jQuery checks whether the click happened on a body #classFilter element. This way, it doesn't matter whether the #classFilter existed when the handler was set. See "Direct and delegated events" in jQuery docs for .on method.
Try to use some reference like 'body' in the event listeners inside your DOM like:
$('body').on('click','.articleButton', function() {
//Do your stuff...
})
$('body').on('click','#classFilter', function() {
//Do your stuff...
})
$('body').on('keypress','#searchbox', function() {
//Do your stuff...
})
$('body').on('click','#logo', function() {
//Do your stuff...
})
This will work that you can fire it more than once.

Add data to bootstrap modal

I have a problem here with bootstrap modals, so in back-end of my app I pull out data from SQL, and I call a JS function like this:
ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowPopup",
"MailLanguageChange('" + Description + "','" + TextResult + "');", true);
And JS looks like this :
function MailLanguageChange(Name, Text) {
$('#MainContent_NewMailTemplate').modal('show');
document.getElementById("Upper_txtDesc").value = Name;
document.getElementById("TextEditorTextArea").innerHTML = Text;
}
So firebug hits break point at this function, so I am sure call of function does work, but here comes the problem, JS is trying to apply this data onto the modal, before all elements of modal are loaded.
But as I use this modal for multiple purpuses ... is there anyway to write it down, "Don't do anything until modal is shown"?
$('#MainContent_NewMailTemplate').modal('show');
As docs says, it returns to the caller before the modal has actually been shown ... how can i by pass that?
EDIT :
This is how I have also tried it
function MailLanguageChange(Name, Text) {
$('#MainContent_NewMailTemplate').modal('show');
$("#MainContent_NewMailTemplate").on('shown.bs.modal', function () {
document.getElementById("Upper_txtDesc").value = Name;
document.getElementById("TextEditorTextArea").innerHTML = Text;
});
}
CONCLUSION :
With use of logic of global variables provided by #Guruprasad Rao
I ended up just simply using
$(document).ready(function () {
document.getElementById("Upper_txtDesc").value = name;
document.getElementById("TextEditorTextArea").innerHTML = text;
});
Thank you
Use twitter-bootstrap's shown.bs.modal method as below:
$("#yourmodalid").on('shown.bs.modal',function(){
//Do whatever you want here
});
There are several other events to look into regarding modal
Update
see you are showing the modal first and then you are registering that event.. So I would suggest you below steps.
Declare 2 global variables at the top in js page.
Ex
var name,text;
Assign them values inside your function MailLanguageChange.
Ex
function MailLanguageChange(Name, Text) {
name=Name;
text=Text;
$('#MainContent_NewMailTemplate').modal('show');
}
Keep shown.bs.modal event somewhere outside the above function
Ex
$("#MainContent_NewMailTemplate").on('shown.bs.modal', function () {
document.getElementById("Upper_txtDesc").value = name;
document.getElementById("TextEditorTextArea").innerHTML = text;
});

How do you get a return value from a colorbox?

I have a colorbox that lets the user select an image. How do I get the file name back from the colorbox? (I have noticed the onClosed function.)
Solution:
As #Gummy sugested i used the onComplete function as the following code exemplifies:
'Return' page:
<input id="colorbox_hidden_return" type="hidden"/>
...
$("#whatever-you-want-to-click-on-to-get-the-color-box").click(function() {
$.colorbox(
{
href: '<?= site_url('the-source-url') . '/' ?>' + id,
height: "600px;",
onClosed: function() { // called when the colorbox closes
var image = $('#colorbox_return_hidden').val();
// ... other processing - what ever the value was is in image
}
});
});
In the colorbox source
var image_name_var = "dynamicaly_change_this_name.png";
$('#submit-or-use-button-id').click(function() {
$('#colorbox_return_hidden').val(image_name_var);
});
Any time while colorbox is open, you can call the element method to retrieve a jQuery object of the current element. From there you can select the element, and access the href property:
href = $.colorbox.element()[0].href;
Also, in any callback the execution context (the value of 'this') will be the current element. So if you wanted to use the onComplete callback for example, you could do something like this:
$('#example').colorbox({onComplete:function(){
href = this.href;
}});
This might do it for you
$(document).bind("cbox_complete", function(){
var href = $.colorbox.element().attr("href");
//do something else
});

Categories

Resources