Click anywhere on body to perform a function: directive - javascript

I have created a directive, which will enable a user to click on a word
to edit it in a text box and then whenever and wherever on body is clicked it should get back to the edited word.
html
<div markdown>bineesh</div>
JS Directive
app.directive('markdown',function () {
/*var htmlText='<textarea cols="20" rows="10" ng-show="isEditMode" ng-dblclick="previewSwitch()" ng-model="markdown"></textarea>';*/
var htmlText='<input type="text" class="form-control" ng-hide="isEditMode" ng-dblclick="backToTextarea()" ng-model="markdown"/>';
var newHtml='<div ng-click="previewSwitch()" ng-show="isEditMode" >{{markdown}}</div>'
var dir={
restrict:'A',
compile:function (tElement,tAttrs,transclude) {
var markdown=tElement.text();
tElement.html(htmlText);
tElement.append(newHtml);
return function (scope,element,attrs) {
scope.isEditMode=true;
scope.markdown=markdown;
scope.previewSwitch=function () {
scope.isEditMode=false;
}
scope.backToTextarea=function () {
scope.isEditMode=true;
}
};
}
}
return dir;
});
I know that something needs to be added in the directive, but I am not getting into it properly, as I am new to Angular

angular.element(document).on('click', function() {
scope.isEditMode = false;
});
element.on('click', function(e) {
e.stopPropagation();
return false;
});

Related

NgTagInput- It's not possible to select the Second tag immediately after the First tag is added?

NgTagInput- It's not possible to select the Second tag immediately after the First tag is added?
We have to focus it outside & again focus inside to show the suggestion box
1) In tagsInput.directive('tagsInput', ...
we have to add code for click event
scope.eventHandlers = {
click: function ($event) {
events.trigger('input-click', $event);
},
2) Then in tagsInput.directive('autoComplete',...
tagsInputConfig.load('autoComplete', $scope, $attrs, {
loadOnClick: [Boolean, false],
3) Then in tagsInput
.on('tag-added tag-removed invalid-tag input-blur', function() {
suggestionList.reset();
})
.on('input-click', function () {
var value = tagsInput.getCurrentTagText();
if (options.loadOnClick) {
suggestionList.load(value, tagsInput.getTags());
}
})
.on('tag-clicked', function () {
event.preventDefault();
event.stopImmediatePropagation();
})
4) Then in Html template
tagsInput.run(["$templateCache", function($templateCache) {
ng-click=\"eventHandlers.input.click($event)\"
ng-blur=\"eventHandlers.input.blur($event)\"
5) then in your HTML code we can loadOnClick set it to true

Toggle between two functions when button clicked.

I have the following button which i am using as a toggle.
<button ng-click="togglefunction()">Toggle Data</button>
Here is the toggle part which should work
$scope.toggleToolPanel = function () {
// need to put below 2 functions here so that when user clicks 1st time, function 1 executes. when user clicks again, function 2 executes and so on.
};
These are 2 functions which should get executed alternatively inside the toggleFunction
function function1(params) {
return '<span >' + data + '</span>';
}
function function2(params) {
return '<span >' + data *100 + '</span>';
}
Add this to your controller:
$scope.firstFunction = false;
Then change your toggleToolPanel to the following:
$scope.toggleToolPanel = function() {
$scope.firstFunction = !$scope.firstFunction;
if($scope.firstFunction) {
function1(params);
} else {
function2(params);
}
};
Toggle a class on the button element each time it's clicked. See classList.toggle. In your click event handler, use classList.contains to look for the presence of toggle. If there do x, if not do y.
Cleaner code is attached below:
angular.module('mainModule', [])
.controller('MainCtrl', ['$scope', function($scope) {
$scope.toggle = function() {
$scope.isToggled = !$scope.isToggled;
var params = $scope.isToggled;
$scope.isToggled ? toggleIn(params) : toggleOut(params);
};
function toggleIn(params) {
console.log(params);
}
function toggleOut(params) {
console.log(params);
}
}]);
<body ng-app="mainModule">
<div ng-controller="MainCtrl">
<input type="button" value="Toggle" ng-click="toggle()" />
</div>
</body>

Using the same jQuery functions but causing conflicts in HTML

Title - Sorry about the title, it was difficult for me to actually explain this.
So I recently finished working on a dynamic fields system using jQuery. This is all working great however I'm wanting to re-use the html for the system over and over again on the same page, this causes problems.
Problem
- When you have duplicates of the form on the same page, and you press 'Add Field' it will run the function and apply the functions to the other classes on the page. (See fiddle for example.)
When you just have one form on the DOM it works fine, but I'm wanting to alter the html slightly so I can use it for different scenarios on a page. I don't want to have separate jQuery files to do this because I don't think it's necessary. I was thinking maybe I could target it's parent containers instead of the class directly? Then I could recycle the same code maybe?
Any suggestions on this guys?
HTML:
<form action="javascript:void(0);" method="POST" autocomplete="off">
<button class="add">Add Field</button>
<div class='input_line'>
<input type="text" name="input_0" placeholder="Input1">
<input type="button" class="duplicate" value="duplicate">
<input type="button" class="remove" value="remove">
</div>
</form>
JQUERY:
$(document).ready(function () {
'use strict';
var input = 1,
blank_line = $('.input_line'),
removing = false;
$('.remove').hide();
$('.add').click(function () {
var newElement = blank_line.clone(true).hide();
$('form').append(newElement);
$(newElement).slideDown();
$('.remove').show();
});
$('form').on('click', '.duplicate', function () {
$(this).parent().clone().hide().insertAfter($(this).parent().after()).slideDown();
$('.input_line').last().before($('.add'));
$('.remove').show();
input = input + 1;
});
$('form').on('click', '.remove', function () {
if (removing) {
return;
} else {
if ($('.input_line').length <= 2) {
$('.remove').hide();
}
$(this).parent().slideUp(function () {
$(this).remove();
removing = false;
});
$('.input_line').last().before($('.add'));
input = input - 1;
}
removing = true;
});
});
Working fiddle - JSFiddle
Problem fiddle - JSFiddle
As you can see in the problem fiddle above, when you duplicate the form it start conflicting. I would like each form to work independently.
Any help would be greatly appreciated!
You need to use closest('form') to find the associated form. Also when looking up the other fields, you need to search within the context of the related form, http://jsfiddle.net/95vaaxsL/7/
function addLine($inputLine) {
var $form = $inputLine.closest('form');
var $newElement = $inputLine.clone(true).hide();
$newElement.insertAfter($inputLine);
$newElement.slideDown();
$form.find('.remove').show();
}
$(document).ready(function () {
'use strict';
$('.remove').hide();
$('.add').click(function () {
addLine($(this).closest('form').find('.input_line:last'));
});
$('form').on('click', '.duplicate', function () {
addLine($(this).closest('.input_line'));
});
$('form').on('click', '.remove', function () {
var $inputLine = $(this).closest('.input_line');
var $form = $inputLine.closest('form');
if ($form.find('.input_line').length < 3) {
$form.find('.remove').hide();
}
$inputLine.slideUp(function(){
$inputLine.remove();
});
});
});
Pulled out the function.

Getting the collection in a jQuery plugin

Basically, what I am trying to do is create a bbcode editor with a textbox, some buttons and jQuery. Here is my form:
<div class="form-group">
<div class="btn-group btn-group-sm">
<button type="button" class="btn glyphicon bbcode" rel="bold"><b>B</b></button>
<button type="button" class="btn glyphicon bbcode" rel="italic"><i>I</i></button>
</div>
</div>
<div class="form-group">
<textarea class="bbcode" rel="editor" cols="100" rows="12"></textarea>
</div>
and my plugin is called using:
<script>
$('document').ready(function() {
$('.bbcode').bbcode();
});
</script>
and the plugin itself, I am just trying to get the basics done at the minute to update the textbox data when a button is clicked:
(function($) {
"use strict";
$.fn.bbcode = function() {
this.click(function() {
var rel = $(this).attr('rel');
if (rel == 'editor') {
return this;
} else {
alert($(this).attr('rel')); // I can see this pop up so the click event is firing
$('.bbcode[rel=editor]').val('test');
return this;
}
});
}
} (jQuery));
This seems to be the only way I can pick up the textbox, I don't really want to hardcode the class I want like that. I think what I am looking for is a way to get the collection from the function call in the script tags.
This is more than likely something stupid/obvious I have overlooked.
The value of this in the immediate function refers to the collection. However, it is shadowed by the this inside your click handler (which refers to the element being clicked) so you cannot access it.
Create a variable to store this and that'll be your collection.
(function ($) {
"use strict";
$.fn.bbcode = function () {
var $editors = this;
this.click(function () {
var rel = $(this).attr('rel');
if (rel == 'editor') {
return this;
} else {
alert($(this).attr('rel')); // I can see this pop up so the click event is firing
$editors.val('test');
return this;
}
});
}
}(jQuery));

Asking user confirmation before redirect to a clicked link

I have a long kind wizard form, like a survey in my site. I want to write a jQuery Function so that when the user click accidentally any link on the page ( except preview and next buttons of the wizard ), it is asked first: are you sure you want to proceed? then it is redirected to the link he clicked, if he click cancel, nothing happens..
So far What i have done is to each link of the page except (next & previw) i have added a class link_ridirect so i can grab all the anchor links. and stop redirecting.
jQuery function is as follow!
<script type="text/javascript">
<!-- HERE IS THE SEARCH FILTER -->
//<![CDATA[
var GLOBAL_NAMESPACE = {};
$(document).ready(function(){
GLOBAL_NAMESPACE.value_changed = true;
});
$(document).ready(function () {
$('.link_redirect').bind('click',function (e) {
e.preventDefault();
if (GLOBAL_NAMESPACE.value_changed){
var res = confirm('you have unsaved changes. Do you want to continue?');
if(res){
window.location.href = $(this).attr('href');
}else{
console.log('stay on same page...');
}
}
});
});
//]]>
</script>
So what i want to do is how can i declare a Global variable to keep track of all field state. So if a field changes, to make it true and call the prevent function.
How about doing this:
$('a').click(function(){return confirm("are you sure?");});
Place it at the bottom of your html, or in the onload of your page, or in the document ready as you suggested in your OP.
edit
If you only want to do this if your variable changesDetected is true, then do it like this:
$('a').click(function(){return !changesDetected || confirm("are you sure?");});
It looks like you have code to interrupt default A-tag clicks already, so the crux of this is to detect when a field has changed such that you want to ask if they want to save before navigating away ?
Here's a JSFiddle Detect Field Changes :
It adds an onchange event to all editable fields whcih sets the global stae to true if something changed.
If the user enters a field then exits without changing, no change is detected.
function setup() {
// bind the change event to all editable fields. Runs on load(or doc ready)
$("input,select").bind("change",function(e) {
GLOBAL_NAMESPACE.value_changed = true;
});
};
you need to use beforeunload event. This event handled when you go out from page.
$(this).on("beforeunload", function () {
return 'are you sure';
});
if you need, that event called not for preview button and next, you can unbind this event handler.
$('#myPreviewButtonId').click(function()
{
console.log('preview clicked');
$(this).unbind("beforeunload");
});
(function($) {
$.fn.checkFileType = function(options) {
var defaults = {
allowedExtensions: [],
success: function() {},
error: function() {}
};
options = $.extend(defaults, options);
return this.each(function() {
$(this).on('change', function() {
var value = $(this).val(),
file = value.toLowerCase(),
extension = file.substring(file.lastIndexOf('.') + 1);
if ($.inArray(extension, options.allowedExtensions) == -1) {
options.error();
$(this).focus();
} else {
options.success();
}
});
});
};
})(jQuery);
$(function() {
$('#image').checkFileType({
allowedExtensions: ['jpg', 'jpeg'],
success: function() {
alert('Success');
},
error: function() {
alert('Error');
}
});
});
label {
display: block;
font-weight: bold;
margin-bottom: 0.5em;
}
<form action="#" method="post" enctype="multipart/form-data">
<div>
<label for="image">Upload image (JPEG only)</label>
<input type="file" name="image" id="image" />
</div>
</form>
You must prevent the default action on a if result of confirm function is false
$(document).ready(function () {
$(".deleteJob").on("click", function (e) {
if (!confirm("Are you Sure want to delete!")) {
e.preventDefault();
}
});
});

Categories

Resources