Global function not executing [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have script that creates a div and adds a function that would remove this div on click, but it's not working.
function del(el) {
$("#"+el).remove();
}
function create() {
var element = document.createElement("div");
var att = document.createAttribute("onclick");
att.value = "del(this.id)";
element.setAttributeNode(att);
$(element).attr('id', "someID");
document.getElementById("someContainer").appendChild(element);
}
Yes, yes, I KNOW this is not the best way to add a function, but I want to do it this way.
Just FYI - after executing create() the DIV appears fine. I checked and it does have proper ID and onclick="del(this.id)" attribute, but after clicking on it nothing happens. I double checked and added alert("I'm working") to the onclick attribute later and that worked. I'm not getting any errors. In the past .remove() was working fine but now it doesn't (Maybe that's because of the way I'm adding a function this time)
EDIT: It appears that del() is not executed when clicking on div.

You have this posted with jQuery, but you're showing mostly Vanilla. As to your initial problem,
function del(el) {
$("#"+el).remove();
}
function create() {
var element = document.createElement("div");
var att = document.createAttribute("onclick");
att.value = "del(this.id)";
element.setAttributeNode(att);
$(element).attr('id', "someID");
document.getElementById("someContainer").appendChild(element);
$(element).html('<h1>DIV CREATED!</h1>').css('background-color', String.randColorHex());
}
create();
#someContainer > div { height: 10em; width: 100%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/JDMcKinstry/String.randColorHex/0c9bb2ff/String.randColorHex.js"></script>
<div id="someContainer"></div>
Seems to work fine.
My guess would be that you have an issue with creating multiple divs by with the same ID, or possibly a scope issue.
Here's a couple steps you might take to double check the issue if using Google Chrome Dev Tools:
Open Console
Double Check function 'del' is globally available and the method you expect it to be by simply typing del. If you get an error, then your method may be displaced.
Another way you could check would be put the following in your onClick: try{console.debug(del);}catch(err){console.error('DEL DOES NOT EXIST!')}
Once you've established the method is within scope, if still not working, try the following:
Replace $("#"+el).remove(); with console.debug(el, $('#'+el))
This does a couple of things: It shows you that the Function is working, as well as gives you information of what's going on within.
If the first part of the console message (el) is the ID you expect, then check the 2nd part ($('#'+el)).
It should look something like: [div:#someID]
Open it and check it's length'. If0`, then it did not find that element.
If 1, then remove should be working fine. Put remove back in just above this console call, and ensure you now get a length of 0
Just FYI, this is how to do what you're trying to do using jQuery.
function create() {
var container = $('#someContainer'), // get container
// create div, everything in {} is an ATTR, then append it TO the container
div = $('<div />', { id: 'someID' + container.children('div').length+1 }).appendTo(container);
// just for visual, i use my own plugin to set a random background color
div.css('background-color', String.randColorHex());
}
$(function() {
$(document) // your click methods
.on('click', '#btnCreate', create)
.on('click', '#someContainer > div', function(e) { $(this).remove(); })
// trigger button once on load
$('#btnCreate').trigger('click');
})
#someContainer > div { height: 2em; width: 100%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/JDMcKinstry/String.randColorHex/0c9bb2ff/String.randColorHex.js"></script>
<button id="btnCreate">Create</button>
<hr />
<div id="someContainer"></div>

Related

Inline CKEditor adds <br> to empty div on startup

CKEditor in Inline mode adds a <br> in the source of the document to an empty div when it is initialized. When you check the source in CKEditor it shows completely empty. I guess this is done to stop collapsing the div or whatever element it is editing on, but for me this is causing issues since I target the empty div with CSS to display a placeholder.
I have searched about everywhere on how to disable this and have seen some issues with FireFox many years ago, but that seems to be unrelated.
<div id="editarea" placeholder="Title"></div>
CKEDITOR.inline('editarea, {});
<style>
div:empty:after {
content: attr(placeholder);
}
</style>
When you look in the Developer Tools the source of the document looks like:
<div id="editarea" placeholder="Title">
<br>
</div>
Adding the following to the config does not seem to be doing anything:
config.fillEmptyBlocks = false;
Can help someone else, the solution I found, pass by the editor event listener:
// Ckeditor 4
editor.on('key', function (evt) {
var selection = editor.getSelection();
var element = selection.getStartElement();
var html = element.getHtml();
var id = element.getId();
if (evt.data.keyCode !== 13
&& id === 'editarea')) {
if (html.match(/( )?<br>$/)) {
element.setHtml('');
}
}
})
That <br> is a "filler" and is always placed at input (editor initialization) into empty block elements by function createBogusAndFillerRules to give an height to the element so the user can click on it to edit it.
Actually there is not a CKeditor configuration to avoid this behaviour but, using jQuery, we can remove the <br> on instanceReady.ckeditor event with:
if($(this).html().trim() === '<br>'){
$(this).html('');
}
Please try this code it is working for me:
For removing br on load
$('your_id').ckeditor();
CKEDITOR.on('instanceReady', function() {
$('div.application').find('br').remove(); // remove br tag added on empty divs
});
for removing &nbsp use this in destroy function:
for(CKname in CKEDITOR.instances) // delete multiple instances of ckeditor
{
CKEDITOR.instances[CKname].destroy(function(){
$("your_id").html(function (i, html) {
return html.replace(/ /g, ''); // remove
});
})
}

.removeClass not functioning within .replaceWith

I'm trying to make a button that will hide a specific -- and then replace it with another hidden . However, when I test the code, everything fires correctly except for the .removeClass which contains the "display: none."
Here is the code:
<script type="text/javascript">
$(document).ready(function(){
var webform = document.getElementById('block-webform-client-block-18');
var unmarriedbutton = document.getElementById('unmarried');
var buyingblock = document.getElementById('block-block-10');
$(unmarriedbutton).click(function () {
$(buyingblock).fadeOut('slow', function() {
$(this).replaceWith(function () {
$(webform).removeClass('hiddenbox')
});
});
});
});
</script>
The CSS on 'hiddenbox' is nothing more than "display: none.'
There is a with the id of unmarried, which when clicked fades out a div and replaces it with a hidden div that removes the class to reveal it. However, the last part doesn't fire -- everything else does and functions properly. When I look at in the console too, it shows no errors.
Can someone please tell me where the error is? Thanks!
Edit: I may be using the wrong function to replace the div with, so here's the site: http://drjohncurtis.com/happily-un-married. If you click the "download the book" button, the the div disappears and is replaced correctly with the div#block-webform-client-block-18. However, it remains hidden.
The function you pass to replaceWith has to return the content you want to replace it with. You have to actually return the content.
I don't know exactly what you're trying to accomplish, but you could use this if the goal is to replace it with the webform object:
$(this).replaceWith(function () {
return($(webform).removeClass('hiddenbox'));
});
NB, use jquery !
var webform = $('#block-webform-client-block-18');
var unmarriedbutton = $('#unmarried');
var buyingblock =$('#block-block-10');
unmarriedbutton.click(function () {
buyingblock.fadeOut('slow', function() {
$(this).replaceWith( webform.removeClass('hiddenbox'));
});
});
Was too fast, i believe it's the way you select your object (getelementbyid) then you create a jquery object from it... -> use jquery API

Prevent closure in jQuery/JavaScript

I'm trying to do something that seems (to me, at least) to be a fairly easy, common thing to do.
Here's the HTML for what I've got on a web page:
<div class="allergiesDiv">
<div>
<span class="editButton">Allergies</span><br />
</div>
<span>Allergies</span>
</div>
</div>
I turn the first <span> into a jQuery button with $('.editButton').button().
(I have many of these pairs on the page.)
What I am trying to do is the following:
When the button is clicked, it loads a jQuery Dialog with the value of the span that follows it loaded into a <textarea>. (BONUS: When the dialog is loaded, I'd like the <textarea> to be focused and all text inside highlighted.)
The user is able to edit the value and then click 'OK'.
When the user clicks 'OK', the Dialog is dismissed and the new value that was entered is used to replace the old value for the span.
Here's the code I'm trying to use (this works OK in IE, but breaks in Mobile Safari and Chrome for PC):
NOTE: I've been chopping the code up some to try to get each problem isolated. I have had this working, at least in IE.
// How I get the button and bind to the click event
$('.editButton')
.button({icons: {primary:'ui-icon-pencil'} })
.click(EditClicked);
// 'Edit' button click handler
function EditClicked() {
var span = $(this).parent().next().children().first();
var text = span[0].innerText;
var dialog = $('<div>').prop('title', 'Edit: ' + $(this).text());
var textArea = $('<textarea>').css('width', '98%').prop('rows', '4').html(text);
textArea.appendTo(dialog);
var windowWidth = $(window).width();
var buttonTop = $(this).button().offset().top;
$(dialog).dialog({
modal: true,
minWidth: windowWidth / 2,
position: ['center',buttonTop],
buttons: {
'Ok' : function () {
OKClicked(span);
},
'Cancel' : function () {
$(this).dialog('close').remove();
}
}
});
textArea.focus().select();
}
// Dialog 'OK' button click handler
function OKClicked(span) {
var text = $(this).find('textarea')[0].innerText;
span.html(text);
$(this).dialog('close').remove();
}
This is currently broken when it gets to var buttonTop..., with the error message of "button is undefined". I haven't yet figured out why that is (I used to have a variable in that method named 'button', but it's gone now. Not sure if that's a caching issue.)
Other than that, can anyone see what's wrong with my process? It seems like I've got some kind of misunderstanding with closure, but I'm not yet good enough with JavaScript to understand how to get the kink out of this code.
what about
var buttonTop = $(this).offset().top;
I am not sure, that $('<div>') is properly syntax for jQuery. Try to use $('div') instead.
When you use $(this).button() - you try to call button method of $(this) object. Seems like a bug.

Jquery UI Dialog Remove Issue

Back from this issue
Multiple Dialog
I was able to solve the issue but now problem is that it removes the div so when I access that Div it give error. It gives error because when I open dialog it works fine after removing on close it gives e.rror
I don't want to removed jQuery('#divPopup') If there is only one div present. If multiple jQuery('#divPopup') are there remove() should be working fine.
jQuery('.register_button_class').live('click',function () {
var iFrameobj = createIframe('',iframeUrl);
jQuery('#divPopup').html(iFrameobj);
createDialogWithClose(url,'#bodyId');
return false;
});
Dummy Div for Dialog Popup, This get removed, when Click on Close Jquery Ui Popup.
So when I say
jQuery('#divPopup').html(iFrameobj);
It gives error.
<div id="divPopup"></div>
I'm assuming that your function:
createDialogWithClose(url, '#bodyId');
removes the div id="divPopup" each from the DOM when you close it.
I would suggest not initially including that div in your markup and change your function to create the div and append it to the DOM when it runs. Then remove like you're already doing.
jQuery('.register_button_class').live('click',function () {
var iFrameobj = createIframe('',iframeUrl);
jQuery("body").append("<div id='divPopup' />").html(iFrameobj);
createDialogWithClose(url,'#bodyId');
return false;
});
It's hard to tell what other issues you may be running into with this bit of code that you posted, however, jQuery("body").append("<div id='divPopup' />").html(iFrameobj); will create the divPopup each time the function runs. So, when you close it and it gets removed it will just get created again the next time that button is clicked.
EDIT: How to check if a Div exists -
if ($("#divPopup").length > 0){
// do something here
}
I solved like this
var length = jQuery('#divPopup').length;
if(length>1)
{
jQuery('#divPopup').dialog('destroy').remove();
}else
{
jQuery('#divPopup').dialog('destroy');
}

Javascript working on Firefox but not in Chrome and IE6

I have javascript that working fine in Firefox 3.x.x, but it does not work in IE*, Chrome, Safari. Simple alert work before calling function. Here is the code
function showDiv(div){
//alert(div);
document.getElementById(div).style.visibility='visible';
document.getElementById(div).style.height='auto';
document.getElementById(div).style.display='block';}
function hideDiv(div){
//alert(div);
document.getElementById(div).style.visibility='hidden';
document.getElementById(div).style.height='0px';
document.getElementById(div).style.display='none';
}
here is the html page code
<td align="center"><a onclick="showDiv('<?=$val['keyname']?>')" style="cursor:pointer;">Edit</a></td>
if I put alert() before showDiv('<?=$val['keyname']?>') then alert box is displayed but the function is not called in other browsers other than fire fox
Please tell me the solution for this.
The syntax looks okay to me.
Make sure there are not multiple elements with the same ID in the document and that your element IDs are valid.
There is nothing inherently wrong in the code you have posted. I suggest you post a reproduceable non-working example: the problem will be elsewhere in the page. Maybe the div ID string isn't unique (this is invalid HTML and will make behaviour unreliable); maybe there's some other script interfering, maybe you have event code firing this that's not written in a cross-browser way
However your attempts to hide an element in three different ways seem like overkill to me. Just a single display change would do it fine.
Another way to do it is to set className='hidden' or '', and use a CSS rule to map that class to display: none. The advantage of this is that you don't have to know whether the element in question is a <div> (that should revert to display: block), a <span> (that should revert to display: inline) or something else. (The table-related elements have particular problems.)
Maybe you could try that:
function showDiv(div) {
var obj = document.getElementById(div);
if (obj) {
obj.style.display = "block";
obj.style.height = "auto";
} else {
alert("DIV with id " + div + " not found. Can't show it.");
}
}
function hideDiv(div) {
var obj = document.getElementById(div);
if (obj) {
obj.style.display = "none";
} else {
alert("DIV with id " + div + " not found. Can't hide it.");
}
}
Do not call document.getElementById several times in the same function, use a variable to store the div element.
The if (obj) test will only execute the code if it has been found by document.getElementById(...).

Categories