.wrap() jQuery-Created Button in jQuery-Created <div> - comments

I am currently using the following script to create a button to show/hide comments on WordPress. However, I would like to wrap the <button> the code generates in a <div>, but I cannot seem to get that portion of the code working properly. Here's the code:
jQuery(document).ready(function() {
// Get #comment-section div
var commentsDiv = jQuery('#comment-section');
// Only do this work if that div isn't empty
if (commentsDiv.length) {
// Hide #comment-section div by default
jQuery(commentsDiv).hide();
// Append a link to show/hide
jQuery('<button/>')
.attr('class', 'toggle-comments')
.attr('href', '#')
.html('Show Comments <span class="icon_comment"></span>')
.insertBefore(commentsDiv);
// Encase button in #toggle-comments-container div
jQuery('<div/>')
.attr('id', 'toggle-comments-container')
.wrap('.toggle-comments');
// When show/hide is clicked
jQuery('.toggle-comments').on('click', function(e) {
e.preventDefault();
// Show/hide the div using jQuery's toggle()
jQuery(commentsDiv).toggle('slow', function() {
// change the text of the anchor
var anchor = jQuery('.toggle-comments');
var anchorText = anchor.html() == 'Show Comments <span class="icon_comment"></span>' ? 'Hide Comments <span class="icon_comment"></span>' : 'Show Comments <span class="icon_comment"></span>';
jQuery(anchor).html(anchorText);
});
});
} // End of commentsDiv.length
});
The code generates the button as expected, but does not wrap it in the <div> as intended.

I think you got the wrap() function wrong
jQuery('.toggle-comments').wrap(jQuery('<div/>', {
id: 'toggle-comments-container'
}))
You need to call the wrap() function on the elements which has to be wrapped(in this case toggle-comments), then pass the element which has to wrap the elements as the argument(in this case the div)

Related

Qtip2- tooltip with hidden element not shown

I´m using the http://qtip2.com/ tooltips. I want to use a hidden element, for that i´m using this code:
<script type="text/javascript">
// <![CDATA[
// Grab all elements with the class "hasTooltip"
$('.hasTooltip').each(function() { // Notice the .each() loop, discussed below
$(this).qtip({
content: {
text: $(this).next('div') // Use the "div" element next to this for the content
}
});
});
// ]]>
And under this code:
<div class="hasTooltip">Hover me to see a tooltip</div>
<div class="hidden">
<!-- This class should hide the element, change it if needed -->
<p><strong>Complex HTML</strong> for your tooltip <em>here</em>!</p>
</div>
If you hover over the "Hover me to see a tooltip", no tooltip is shown? No idea, why?
events: {
render: (event, api) ->
show: (event, api) ->
$('.qtip:visible').qtip('hide')
elements = $(api.get('content.text')).removeClass('hidden')
api.set('content.text', elements)
,
hide: (event, api) ->
}
I think its a bug in Qtip2, i had to manually remove the class

CKEDITOR - how to add permanent onclick event?

I am looking for a way to make the CKEDITOR wysiwyg content interactive. This means for example adding some onclick events to the specific elements. I can do something like this:
CKEDITOR.instances['editor1'].document.getById('someid').setAttribute('onclick','alert("blabla")');
After processing this action it works nice. But consequently if I change the mode to source-mode and then return to wysiwyg-mode, the javascript won't run. The onclick action is still visible in the source-mode, but is not rendered inside the textarea element.
However, it is interesting, that this works fine everytime:
CKEDITOR.instances['editor1'].document.getById('id1').setAttribute('style','cursor: pointer;');
And it is also not rendered inside the textarea element! How is it possible? What is the best way to work with onclick and onmouse events of CKEDITOR content elements?
I tried manually write this by the source-mode:
<html>
<head>
<title></title>
</head>
<body>
<p>
This is some <strong id="id1" onclick="alert('blabla');" style="cursor: pointer;">sample text</strong>. You are using CKEditor.</p>
</body>
</html>
And the Javascript (onclick action) does not work. Any ideas?
Thanks a lot!
My final solution:
editor.on('contentDom', function() {
var elements = editor.document.getElementsByTag('span');
for (var i = 0, c = elements.count(); i < c; i++) {
var e = new CKEDITOR.dom.element(elements.$.item(i));
if (hasSemanticAttribute(e)) {
// leve tlacitko mysi - obsluha
e.on('click', function() {
if (this.getAttribute('class') === marked) {
if (editor.document.$.getElementsByClassName(marked_unique).length > 0) {
this.removeAttribute('class');
} else {
this.setAttribute('class', marked_unique);
}
} else if (this.getAttribute('class') === marked_unique) {
this.removeAttribute('class');
} else {
this.setAttribute('class', marked);
}
});
}
}
});
Filtering (only CKEditor >=4.1)
This attribute is removed because CKEditor does not allow it. This filtering system is called Advanced Content Filter and you can read about it here:
http://ckeditor.com/blog/Upgrading-to-CKEditor-4.1
http://ckeditor.com/blog/CKEditor-4.1-Released
Advanced Content Filter guide
In short - you need to configure editor to allow onclick attributes on some elements. For example:
CKEDITOR.replace( 'editor1', {
extraAllowedContent: 'strong[onclick]'
} );
Read more here: config.extraAllowedContent.
on* attributes inside CKEditor
CKEditor encodes on* attributes when loading content so they are not breaking editing features. For example, onmouseout becomes data-cke-pa-onmouseout inside editor and then, when getting data from editor, this attributes is decoded.
There's no configuration option for this, because it wouldn't make sense.
Note: As you're setting attribute for element inside editor's editable element, you should set it to the protected format:
element.setAttribute( 'data-cke-pa-onclick', 'alert("blabla")' );
Clickable elements in CKEditor
If you want to observe click events in editor, then this is the correct solution:
editor.on( 'contentDom', function() {
var element = editor.document.getById( 'foo' );
editor.editable().attachListener( element, 'click', function( evt ) {
// ...
// Get the event target (needed for events delegation).
evt.data.getTarget();
} );
} );
Check the documentation for editor#contentDom event which is very important in such cases.

Angular ng-click on inputed later on dom

i'm changing a innter html of a dom element with a button. And when button is clicked i want to fire another controller function. Something like that. ... But is not working :).
$scope.addBtn = function() {
$('domtarget').html('<button ng-click="removeButton();"></button>');
}
$scope.removeBtn = function() {
$('domtarget').html('');
}
Please suggest fix :)
Do not modify DOM inside your controller, ever.
<div ng-show="showMe"></div>
<button ng-click="showMe = !showMe;anotherAction()">Switch</button>
<button ng-click="someOtherAction()">Switch2</button>
.
function SomeCtrl($scope) {
$scope.showMe=true;
$scope.anotherAction = function () {
alert("gotcha");
};
$scope.someOtherAction = function () {
$scope.showMe = !$scope.showMe;
$scope.anotherAction();
};
}
For hiding/showing an element conditionally, use ng-show or ng-hide.
For firing an event on click, use ng-click

jQuery .on() event doesn't work for dynamically added element

I'm making a project where a whole div with buttons is being inserted dynamically when user click a button, and inside that div there's a button, which when the user click on it, it does something else, like alerting something for example.
The problem is when i press on that button in the dynamically added div, nothing happens. The event doesn't fire at all.
I tried to add that div inside the HTML and try again, the event worked. So i guess it's because the div is dynamically added.
The added div has a class mainTaskWrapper, and the button has a class checkButton.
The event is attached using .on() at the end of script.js file below.
Here's my code :
helper_main_task.js : (that's the object that adds the div, you don't have to read it, as i think it's all about that div being dynamically added, but i'll put it in case you needed to)
var MainUtil = {
tasksArr : [],
catArr : ["all"],
add : function(){
var MTLabel = $("#mainTaskInput").val(), //task label
MTCategory = $("#mainCatInput").val(), //task category
MTPriority = $("#prioritySlider").slider("value"), //task priority
MTContents = $('<div class="wholeTask">\
<div class="mainTaskWrapper clearfix">\
<div class="mainMarker"></div>\
<label class="mainTaskLabel"></label>\
<div class="holder"></div>\
<div class="subTrigger"></div>\
<div class="checkButton"></div>\
<div class="optTrigger"></div>\
<div class="addSubButton"></div>\
<div class="mainOptions">\
<ul>\
<li id="mainInfo">Details</li>\
<li id="mainEdit">Edit</li>\
<li id="mainDelete">Delete</li>\
</ul>\
</div>\
</div>\
</div>');
this.tasksArr.push(MTLabel);
//setting label
MTContents.find(".mainTaskLabel").text(MTLabel);
//setting category
if(MTCategory == ""){
MTCategory = "uncategorized";
}
MTContents.attr('data-cat', MTCategory);
if(this.catArr.indexOf(MTCategory) == -1){
this.catArr.push(MTCategory);
$("#categories ul").append("<li>" + MTCategory +"</li>");
}
$("#mainCatInput").autocomplete("option", "source",this.catArr);
//setting priority marker color
if(MTPriority == 2){
MTContents.find(".mainMarker").css("background-color", "red");
} else if(MTPriority == 1){
MTContents.find(".mainMarker").css("background-color", "black");
} else if(MTPriority == 0){
MTContents.find(".mainMarker").css("background-color", "blue");
}
MTContents.hide();
$("#tasksWrapper").prepend(MTContents);
MTContents.slideDown(100);
$("#tasksWrapper").sortable({
axis: "y",
scroll: "true",
scrollSpeed : 10,
scrollSensitivity: 10,
handle: $(".holder")
});
}
};
script.js : (the file where the .on() function resides at the bottom)
$(function(){
$("#addMain, #mainCatInput").on('click keypress', function(evt){
if(evt.type == "click" || evt.type =="keypress"){
if((evt.type =="click" && evt.target.id == "addMain") ||
(evt.which == 13 && evt.target.id=="mainCatInput")){
MainUtil.add();
}
}
});
//Here's the event i'm talking about :
$("div.mainTaskWrapper").on('click', '.checkButton' , function(){
alert("test text");
});
});
It does not look like div.mainTaskWrapper exist.
From the documentation (yes, it is actually bold):
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page.
[...]
By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.
You might want to bind it to #tasksWrapper instead:
$("#tasksWrapper").on('click', '.checkButton' , function(){
alert("test text");
});
You need to specify a selector with on (as a parameter) to make it behave like the old delegate method. If you don't do that, the event will only be linked to the elements that currenly match div.mainTaskWrapper (which do not exists yet). You need to either re-assign the event after you added the new elements, or add the event to an element that already exists, like #tasksWrapper or the document itself.
See 'Direct and delegate events' on this page.
I know this is an old post but might be useful for anyone else who comes across...
You could try:
jQuery('body')on.('DOMNodeInserted', '#yourdynamicallyaddeddiv', function () {
//Your button click event
});
Here's a quick example - https://jsfiddle.net/8b0e2auu/

I need help using jquery to post info from Pop Up to an MVC 3 Controller action

So I have a view that allows users to Approve or Reject items listed on the page. When approved, I simply use the #Ajax.ActionLink to post to the appropriate controller action. When the user Rejects an item, the user is required to enter a reason for the rejection. I'm found code on the internet that gave me a popup dialog and added a textbox and OK/Cancel buttons. I can capture the input from the user and show it in an alert, but now I need to complete it and I'm not sure how.
1st - I need add functionality to pass to my jquery link handler, the ID associated with the Item being rejected.
2nd - I need a way to call my Controller Action from the jquery.
Here is the code I have up to this point.
My link is simply an 'a' tag. I can't see to post the code for this without removing the <>
a href="#dialog" name="modal" Reject a
My script handles this here
$(document).ready(function () {
//select all the a tag with name equal to modal
$('a[name=modal]').click(function (e) {
//Cancel the link behavior
e.preventDefault();
//Get the A tag
var id = $(this).attr('href');
//Get the screen height and width
var maskHeight = $(document).height();
var maskWidth = $(window).width();
//Set heigth and width to mask to fill up the whole screen
$('#mask').css({ 'width': maskWidth, 'height': maskHeight });
//transition effect
$('#mask').fadeIn(1000);
$('#mask').fadeTo("slow", 0.8);
//Get the window height and width
var winH = $(window).height();
var winW = $(window).width();
//Set the popup window to center
$(id).css('top', winH / 2 - $(id).height() / 2);
$(id).css('left', winW / 2 - $(id).width() / 2);
//transition effect
$(id).val('');
$(id).fadeIn(2000);
});
Here is my pop up dialog and the mask that grays out the screen when the dialog is opened.
<div id="boxes">
<div id="dialog" class="window">
Enter the reason for rejection:</br>
<textarea class="multiline" id="rejectreason" rows="10" cols="20"></textarea><br/>
<div style="margin-left: 120px"><input type="button" value="OK" class="ok" style="width:70px"/> <input type="button" value="Cancel" style="width:70px" class="close"/>
</div>
</div>
<!-- Mask to cover the whole screen -->
<div id="mask"></div>
</div>
It could be that I'm going about this completely wrong, but it's all I could find on line and pieced it all together from there. As this is my first experience with jquery and MVC, I'm struggling a bit here. Any help would be greatly appreciated.
Thanks
UPDATE
OK, so I added a data-id attribute to my link that allows me to get the ID of the link clicked. I tested it using this code and it works.
var iD = $(this).attr('data-id');
I now need to pass this value to my dialog so I can then retrieve it again when the OK button on the dialog is clicked. I can set a hidden field on the page if necessary and retrieve it from there.
Here is some code to get you on the right path...
jQuery Ajax:
$(document).ready(function () {
$("#InputButtonId").click(function () {
$.ajax({
url: '#Url.Action("SomeAction", "Controller")',
type: 'POST',
data: { id: $("#hidden").val(), reason: $("#rejectreason").html },
dataType: "json",
beforeSend: function () {
},
success: function (result) {
// Do action if success
},
error: function (result) {
// Do action if error
}
});
return false;
});
});
And the controller action:
[HttpPost]
public JsonResult SomeAction(string id, string reason)
{
//Perform Actions
return Json(new
{
value1 = value1,
value2 = value2
}, JsonRequestBehavior.AllowGet);
}
Hope this helps.

Resources