cannot call javascript method from within tinymce editor - javascript

I am trying to make a javascript method call from within the tinymce editor on click event on a piece of text written inside the editor, but it is not working. Tinymce version 4 is being used by me.
Below mentioned is the code snippet. Though i can successfully call the inline alert method as in second div, i am unable to call my custom javascript method as in first div.
Suggestions would be much appreciated.
<script type="text/javascript" src="tinymce/js/tinymce/tinymce.min.js"></script>
<script type="text/javascript">
function customMethod(){
alert('custom method not being called !!');
}
tinymce.init({
selector: "textarea",
valid_elements: "*[*]"
});
</script>
<form method="post">
<textarea name="content" style="width:100%">
<div onclick="customMethod();">Call custom method.</div>
<div onclick="alert('alert called');">Call Alert.</div>
</textarea>
</form>

You have two options: First you add onclick as valid attribute to your divs (see tinymce configuration paramter valid_elements). Here is an example configuration
valid_elements: "#[id|class|title|style|onmouseover|onclick]," +
"a[name|href|target|title|alt]," +
"#div,blockquote,-ol,-ul,-li,br,img[src|height|width],-sub,-sup,-b,-i,-u," +
"-span[data-mce-type],hr",
Second option is to add this setup parameter you your tinymce config catching each onclick event in the editor
setup : function(ed) {
// Display an alert onclick
ed.on('click', function(evt) {
console.log('User clicked the editor. Element:', evt.target);
if (evt.target.className == 'do_1') alert('do_1');
if (evt.target.className == 'do_2') alert('do_2');
});
},
You may want to have a look at this tinymce fiddle to see it in action: http://fiddle.tinymce.com/QXdaab

Related

jquery - event handler works if pasted into Console but not when included through .js file

I have an application using jquery 3.2.1
One of the pages contains 2 <form> elements which have the same class name, .products-ctp__search-form. The HTML for this is rendered on page load:
<form class="products-ctp__search-form">
<input name="n1" type="text">
</form>
<form class="products-ctp__search-form">
<input name="n2" type="text">
</form>
I want to target the <input> elements in each form and use an event handler to deal with the user entering input into either of them. So I've written this inside a foo.js file and then linked it at the bottom of the page:
<!-- Form markup above is here -->
<script src="foo.js"></script>
The foo.js file contains:
$(function() {
$('.products-ctp__search-form input[type="text"]').bind("keyup change input",
function (e) {
console.log('debug');
console.log(e);
});
});
When I enter text into either input it doesn't log anything to the console.
But if I paste the script above into my console, it will, e.g.
debug
VM726:4 r.Event {originalEvent: InputEvent, type: "input", target: input#n1.form-control.form-control.input-border-secondary, currentTarget: input#n1.form-control.form-control.input-border-secondary, isDefaultPrevented: ƒ, …}
Strangely if I get rid of 1 of the inputs (e.g. removing the form containing n2 and keeping n1) it works fine. Other pages in the application have just 1 input and the equivalent code - when included from a linked .js file - works fine.
So I've read jquery works in console, but not in linked js file but this seems to suggest waiting for something to load. In this case the markup is rendered on page load (not via ajax, etc) and the jquery code is inside document.ready.
There is another post jQuery works in console but not in .js file which I read but again this seems to suggest having to wait for something to load. If this is the case then what am I supposed to wait for and how to I bind this?
The linked posts make sense when you're waiting for something like an image to load. But how does this work if it's just the markup of the page? Or is that not actually the problem?
jquery is included in the <head> of the document whereas the foo.js file is inside <body>. So I don't believe it's an issue of foo.js being included before jquery, etc.
I have tried your code and found that console.log(e) is causing issue (not sure why it is throwing error in console). Comment this part and don't use bind, use 'on' as bind is deprecated in jquery.
$(function() {
$(document).on("keyup change input", '.products-ctp__search-form input[type="text"]', function (e) {
console.log('debug');
//console.log(e);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<form class="products-ctp__search-form">
<input name="n1" type="text">
</form>
<form class="products-ctp__search-form">
<input name="n2" type="text">
</form>

$.fn.submit() event don't trigger inside an <iframe>

Simply speaking, I have a form, and a field.
<!-- inner.html -->
<form id="inner_form">
<input type="text" name="username" />
<input type="submit" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
$('#inner_form').submit(function() {
alert('Inner submit is triggered!');
});
});
</script>
The above code goes well: when I click the submit button, it triggers the submit event of #inner_form, and alerts the sentence: Inner submit is triggered!
My problem is, when I make another page, and loads the inner.html inside an <iframe>:
<!-- outer.html -->
<iframe id="the_frame" src="inner.html">
</iframe>
<button id="outer_submit">Submit Inner</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
$('#outer_submit').click(function() {
// it don't trigger the inner submit() event!
$('#the_frame').contents().find('#inner_form').submit();
});
});
</script>
As the above code (which might not working well in the snnipet), I click the #outer_submit button, and the #inner_form do submitted, but the event I defined inside it don't triggered!
Why do this happen? And if I want the inner event triggered well with outer action, how can I got it?
While I can't give you an answer as to 'why', here's some discoveries I made while testing this:
Replacing the .submit() action with
$('#the_frame').contents().find('#inner_form input[type="submit"]').click();
Will trigger the alert. This isn't a proper fix though, because there's more ways to submit a form. Still, it shows that the events are not completely broken. So I dug deeper.
I tried using native javascript events instead of jquery's .submit([function]) bind in inner.html:
<form id="inner_form" onsubmit="alert('hi')">
That actually shows the alert. And so does this:
$('#inner_form')[0].onsubmit = function() {
alert('Inner submit is triggered!');
}
So there seems to be something wrong with the way jQuery sets and/or detects its own submit() method.
One more try:
$('#inner_form').on('submit', function() {
alert('Inner submit is triggered!');
});
This also shows the submit!
My wild guess is that for some reason when the events in inner.html are being bound, it doesn't know the form yet, even though the bind is wrapped in an implicit document.ready event through $(function(){ .. });.
As for the how and why of this I remain in the dark, but the fix is simple: wrap your event binds in an .on() method.

magnific-popup passing a variable

I'm trying to make magnific popup contain some forms. I would like to pass variables through the html anchor to the final popup.
As Var1 in this pseudocode:
<!-- HTML launcher element -->
Show inline popup
<!-- Popup itself -->
<div id="test-popup">
<form method="post" action="">
<input type="hidden" id="myVar" name="Var1" value="[placeholder]" />
<input type="submit" />
</form>
</div>
<!-- Inizialization -->
<script type="text/javascript">
$(document).ready(function() {
$('.open_popup_link').magnificPopup({
type:'inline',
midClick: true,
function() {
**Here some magic code that sets Var1 = X **
$('#myVar').attr('value', function(i, attr){
return attr.replace('[placeholder]', Var1);
});}
});
});
</script>
I need this because I will generate serverside (w. PHP) the launchers so that each link will generate different form data.
edit: One approach i thought at was to use custom attributes in the launcher, eg:
Show inline popup
But I couldn't really get the right jQuery syntax for nesting the attributes processing INSIDE the magnific-popup inizialization.
My js/jquery knowledge is very basic, so thank you for any hint.
How about using a separate click handler outside the magnificPopup settings that changes the value of your input whenever a link is clicked, just make sure to bind it before initializing the plugin
HTML
Using data attributes as correctly suggested
Show inline popup
Javascript
$('.open-popup-link').click(function(){
$('#myVar').val($(this).data('var1'));
});
$('.open_popup_link').magnificPopup({
type:'inline',
midClick: true
});
Try:
Javascript/jQuery
<script type="text/javascript">
$(document).ready(function() {
$('.open_popup_link').magnificPopup({
type:'inline',
midClick: true,
function() {
**Here some magic code that sets Var1 = X **
Var1 = $('#myVar').val();
});}
});
});
Not quite sure what you are using Var1 for, but that is how you would get the value from the input into a global Var1 variable.
Let me know if I didn't understand what you're trying to do correctly.

jQuery .on click event does not occur

Hi and thanks for reading. I've been trying to avoid using HTML onclick="__" references and instead putting these events in my .js file. After reading about jQuery's .click() and then .on() events, I tried to use this in my code for a button.
edit In my haste to make up a <p> that didn't have the rest of the contents, I entered "name" instead of "id". Many answers have recommended I either switch to a p[name=p+ or #p+ reference, but my main problem has been that I can't even hit the alert before the reference to the id/name. Thanks again for your answers.
HTML:
<p name="pBananas"> junk </p>
<button class="deleter" id="dBananas" name="Bananas">Delete</button>
JS:
$(document).ready(function() {
$('.deleter').click(function() {
alert('click function works');
$("p" + $(this).attr("name")).remove();
});
});
The above code won't even get to the alert when I click the button. I've also tried referring to the button by name and ID, and going by $(document).ready($('.deleter')___.
I tried using the $(handler) format as well to have the click event be set after the document is ready. Neither way seems to work. At this point, I resorted to onclick="deleteButton()" and have a deleteButton() function in my .js file, but the function won't detect $(this) and just deletes all <p> tags.
The rest of my javascript is working. I haven't tried including this .on() at the bottom of the HTML, but I'm trying to avoid scripts in my HTML as well. For completeness' sake, I've been testing on both Chrome and Firefox, using a .jsp file to render the HTML.
Thanks again.
Edits
here's how I'm referencing my jquery and js, directly copy-pasted.
<script type="text/javascript"
src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="javascript/index.js"></script>
</head>
here is how my html looks leading up to the div where the is inserted:
<body>
<div id="wrapper">
<div id="header">Card Draw Probability Calculator</div>
<div id="main">
<div id="cardList">
<fieldset>
<legend> Select cards for probability calculation</legend>
<div id="innerCardList"></div>
Here is how the <p> is generated:
function newestCardListLineMaker() {
var $newLine = $('<p id="newestPara"><input type="checkbox" name="new" value="none"/> <input class="cardText" type="text" maxlength="30" name="newestCard" /> Quantity <input type="text" maxlength="1" class="quantityText" name="newestQuant" /><button class="deleter" id="newestDelete">Delete</button><br/></p>');
$("#innerCardList").append($newLine);
On another note, which I should have seen before as significant: the HTML that the .click or .on(click, handler) is referencing has been created by another js function.
Try using .on() function, so your code would be:
$(document).ready({
$('.deleter').on('click', function(){
//do stuff here
});
});
Even better would be this:
$(document).ready({
$('div_above_.deleter').on('click', '.deleter', function(){
// do stuff here
});
});
Hope this helps you.
I have modify your javascript code check it.
$('.deleter').click(function() {
alert('click function works');
var p="p"+$(this).attr("name");
$('p[name='+p+']').remove();
});
working demo
<p id="pBananas"> junk </p>
<button class="deleter" id="dBananas" name="Bananas">Delete</button>​
$(document).ready(function() {
$('.deleter').click(function() {
alert('click function works');
$("#p" + $(this).attr("name")).hide();
});
});​
Edited Jsfiddle
For me it works. Didn't delete the Paragraph element though so your code should look like this instead:
<p id="pBananas"> junk </p>
<button class="deleter" id="dBananas" name="Bananas">Delete</button>
and
$(document).ready(function() {
$('.deleter').click(function() {
alert('click function works');
$("#p" + $(this).attr("name")).remove();
});
});
$(document).ready(function() {
$('.deleter').click(function() {
alert('click function works');
//alert($(this).attr("name"));
$("p[name=p" + $(this).attr("name") + "]").remove();
});
});​
The final code I used to complete the .on('click') event was:
$(document).ready(function() {
$("div#innerCardList").on("click", "button.deleter", function() {
var paraName = $(this).closest("p").attr("id");
$("#" + paraName).remove();
});
});
The HTML elements which I wanted to assign click events to were generated after the page was already loaded. I needed to delegate the events to the containing div.
Thanks for all the help and different perspectives!

jQuery UI modal confirmation dialog with ASP.NET not firing onClick event

jQuery newbie here. I've looked at dozens of similar questions on this site, as well as the answers provided so far here, all having pretty much the same response, and I've tried all of them, but nothing is working for me.
For the Javascript code in my .aspx, I currently have:
<script type="text/javascript" src="/resources/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="/resources/jquery-ui-1.8.20.custom.min.js"></script>
<link rel="stylesheet" type="text/css" href="/resources/ui-lightness/jquery-ui-1.8.20.custom.css" />
<script language="javascript" type="text/javascript">
$(function() {
var $myDialog = $("#cancelDialog").dialog({
autoOpen: false,
modal: true,
buttons: {
'Yes, cancel': function() {
$(this).dialog('close');
return true;
},
'No, resume editing': function() {
$(this).dialog('close');
return false;
}
}
});
$("[id$=btnCancel]").click(function(e) {
//e.preventDefault();
alert('boo');
//$myDialog.dialog('open');
});
});
</script>
The markup for "btnCancel" looks like this - notice that I don't have an "onClientClick" attribute because jQuery is supposed to do this for me, right?
<asp:Button ID="btnCancel" CssClass="btnCancel" runat="server" Text="Cancel"
CausesValidation="false" UseSubmitBehavior="false" />
And here's the markup I have for the cancellation dialog:
<div id="cancelDialog" style="display: none;" title="Please confirm cancellation">
<p>Are you sure you wish to cancel and abandon your changes?</p>
</div>
According to all the examples I've seen (and the answers provided here), this should give me a jQuery UI popup with my two buttons that just works. The page is no longer posting back when I hit the cancel button (due to the changes I made at Patrick Scott's suggestion). I could just use a standard Javascript confirm() dialog for this, but I want to be able to customize the prompts/styling.
The only other information I can think of to throw in is that this code is on an ASP.NET Wizard control (the cancel button is in the StepNavigationTemplate), but that shouldn't matter, should it?
Any hints as to what I need to change to get this working are greatly appreciated!
(question & code updated to reflect recent changes I've made)
The reason it isn't working is because the ID of the button changes when it's rendered to the page. To access the control in JavaScript, you need to use the ClientID property:
$("#<%= btnCancel.ClientID %>").click(function(e){
//open the dialog
});
Use $("[id$=btnCancel]") as your selector for the click event..
$= means ends with in the jquery selector, and webforms adds a bunch of stuff that will make your id not match.
$("[id$=btnCancel]").click(function(e) {
I also don't understand why you have the buttons declared separately from the rest of the dialog...
do this instead:
$(function() {
var $myDialog = $("#cancelDialog").dialog({
autoOpen: false,
modal: true,
buttons: {
'Yes, cancel': function() {
$(this).dialog('close');
return true;
},
'No, resume editing': function() {
$(this).dialog('close');
return false;
}
}
});
$("[id$=btnCancel]").click(function(e) {
e.preventDefault();
$myDialog.dialog('open');
});
});
you need to break it down - it sounds like there is another error in the JS somewhere which you don't see because the page is reposting. Try an alert on the click:
$('#btnCancel').click(function(e) {
alert('boo');
});
If this doesn't work you need to make the simplest script possible get that working and then add to it.
I figured it out! It turns out that <script> tags (nor most other tags, it seems) cannot be self-closed in HTML4 or HTML5. I was writing them like so:
<script type="text/javascript" src="whatever" />
when according to the standard, they must be written like so:
<script type="text/javascript" src="whatever"></script>
This was allowing my first <script> include to work (jquery-1.7.2.min.js), but following ones to fail. Weird, huh?
Here are some links with supporting information:
http://www.w3.org/TR/html4/interact/scripts.html#h-18.2.1 (the HTML4 specification)
Can the <script> tag not be self closed?
http://tiffanybbrown.com/2011/03/23/html5-does-not-allow-self-closing-tags/
<%=this.Page.ClientScript.GetPostBackEventReference(new PostBackOptions(this.Button1))%>;
Hook this to the "yes" button on your modal confirmation dialog. You'll need to change the ID according to your needs.

Categories

Resources