jQuery plugin overwrite all css or only some attributes - javascript

I'm creating a simple jQuery plugin for my web app. Right now i'm adding a 'settings' option, which can be used to change the default CSS for the selected elements:
Html
<script type="text/javascript">
var mycss = {tagNormalStyle: {backgroundColor: '#ddd', color:'#222'}};
$(document).ready(function(){
$("#tag1").tagme(mycss);
$("#tag2").tagme(null);
});
</script>
jQuery plugin
$.fn.tagme = function(options) {
// some defaults
var settings = $.extend({
tagNormalStyle:{
backgroundColor: 'black',
color: 'white',
marginLeft: '5px',
marginTop: '5px',
padding: '5px',
float: 'left',
borderRadius: '5px'
},
//more stuff here...,
options
};
}
In my code, i'm using something like:
if (condition)
tag.css = settings.tagNormalStyle;
The problem is, what if the user only needs to change the color, for example?
var mycss = {tagNormalStyle: {color:'#222'}};
$("#tag1").tagme(mycss);
Now all the defaults are gone for tagNormalStyle! How can i avoid to 'hard-code' every css property on my settings object? Maybe i could 'merge' the defaults and options objects.
Any ideas?
Thanks!

pass true as the first parameter to the extend function.
something like:
$.extend(true,obj1,obj2)

Related

Fabric.js iText : How to do text selection on iText while not allowing text modification?

I have been reading docs and forums to solve this problem, but could not find an answer.
var t1 = canvas.t1 = _t1 = new fabric.IText(text1, {
left: 100,
top: 50,
editable: true,
selectable: false,
width: 300,
height: 150,
fontFamily: 'Helvetica',
fontSize: 20,
fill: '#f4b642',
} );
var t2 = canvas.t2 = _t1 = new fabric.IText(text2, {
left: 200,
top: 150,
editable: false,
selectable: true,
width: 300,
height: 150,
fontFamily: 'Helvetica',
fontSize: 20,
fill: '#333',
} );
canvas.add(t1,t2);
t1.enterEditing();
https://jsfiddle.net/qgeryu9o/2/
As shown on the fiddle by the upper iText element , I would like to
access directly to the text at page load , this just to select
some words or sentences.
Using itext.enterEditing(), as on the upper itext box, this works fine except
that it allows also what I do not want : to delete, add, or modify the text.
In setting itext.editable to false ( as on fiddle lower iText element)
the text cannot be modified , but there is no way to show selection.
I tried to catch keydown events on the container div as suggested on this thread.
fabric.js canvas listen for keyboard events?
But it does not work for me (tried on Chrome, Firefox), the event is not fired on itext in editing mode.
Thanks for your help.
Mike
Since I could not find a Fabric.js parameter allowing selection but no editing, I used a work-around.
At first I wanted to remove listeners set on the hidden textarea.
But, as bind() is used , there is no way to remove these listeners
without modifying fabric.js :
fabric.util.addListener(this.hiddenTextarea, 'keydown', this.onKeyDown.bind(this));
fabric.util.addListener(this.hiddenTextarea, 'keyup', this.onKeyUp.bind(this));
So, I just have overwritten the onInput() and onKeydown methods.
t1.onInput = function() {
console.log("no input on t1") ;
return false } ;
t1.onKeyDown = function() {
console.log("no onKeyDown on t1") ;
return false } ;
It works fine as shown on the corrected fiddle:
https://jsfiddle.net/qgeryu9o/4/
If there is a more direct way to get the same result (selection but no edition), I would be happy to hear about it.
Thanks

My background Image won't show up on the div

I am trying to create a div and add a background image to it in jQuery. For some reason, I cannot do it. If I instead make my background color white, I get a white background. Here is my code:
function appendToDom(poster) {
var aPoster = $('<div>');
aPoster.css({
display: 'inline block',
float: 'left',
margin: '10px',
marginLeft: '37px',
marginTop: '20px',
width: '200px',
height: '300px',
fontSize: '36px',
color: 'black',
//backgroundColor: 'white',
backgroundSize: '200px 300px',
backgroundImage: './../images/question.png'
})
/*
$(aPoster).attr("css","background-image: url(~/desktop/MyMovies/public/js/images/question.jpeg)");
$(aPoster).attr("css","background-size: 200px 300px");*/
$(main).append(aPoster);
}
Thanks for all the advice! So I took the suggestions given to me, but it still doesn't work for me.Here is a screenshot of what I have:
my improved code
NVM I got it! Thanks!
Try making your method look like this...
aPoster.css({
'display': 'inline block',
'float': 'left',
'margin': 10,
'margin-left': 37,
'margin-top': 20,
'width': 200,
'height': 300,
'font-size': 36,
'color': 'black',
'background-color': 'white',
'background-size': '200px 300px',
'background-image': 'url("./../images/question.png")'
Try something like this and see what you get. You also notice that I got rid of the values with pixel. Because JavaScript's default values for CSS properties like that have their units in pixels. Just try it and see if it works. Hope this helped. Oh and one last thing, if you used an external script, don't forget to use the URL and make it relative to the script itself and not your main page...but in your case, the styles would be added inline to the div element so you should probably make it relative to your main page, the page where the div would be created...
If the style is inline like in your case, the path has to be relative to the html document. Please check it.

fabric js fontweight not working

I am using this code to add textbox in canvas using fabric js,
var text = 'Type Text Here';
var textSample = new fabric.Textbox(text, {
left: getCardLeft() + 100,
top: getCardTop() + 10,
width: 200,
height: 20,
fontFamily: 'Helvetica',
fill: getColorPickerForegroundColor(),
fontWeight: '',
fontSize: parseInt('25'),
originX: 'center',
hasRotatingPoint: true,
centerTransform: true,
});
canvas.add(textSample);
Which successfully add textbox into canvas.
Now, if i try to make it bold using this command
canvas.getActiveObject().set("fontWeight", "bold");
canvas.renderAll();
Working, But when try to change it to normal,
canvas.getActiveObject().set("fontWeight", "");
canvas.getActiveObject().set("fontWeight", "100");
canvas.getActiveObject().set("fontWeight", "normal");
canvas.renderAll();
not working.
I don't know where the issue is. Am i doing anything wrong here?.
Its behaving strange
You can see it here.
visit first here
Then visit here
I just take fabric.js from here and replaced with mine, and working all.
The following code works for me. I see two points where I could failed at your side:
canvas.renderAll();
Needed to be rerendered properly. And also:
canvas.setActiveObject(textSample);
was neccessary for me. Because otherwise:
canvas.getActiveObject();
was undefined.
Now a full working code example:
var canvas = new fabric.Canvas('c', { selection: false });
var text = 'Type Text Here';
var textSample = new fabric.Textbox(text, {
left: 300,
top: 50,
width: 200,
height: 20,
fontFamily: 'Helvetica',
fill: "#fac",
fontWeight: '100',
fontSize: parseInt('25'),
originX: 'center',
hasRotatingPoint: true,
centerTransform: true,
});
canvas.add(textSample);
canvas.setActiveObject(textSample);
canvas.getActiveObject().set("fontWeight", "bold");
canvas.renderAll();
canvas.getActiveObject().set("fontWeight", "100");
canvas.renderAll();
Hope that helps.

Open page from bookmarklet, but, make it like a modal window?

I am using a bookmarklet which can (obviously) be called by the user anywhere:
javascript:(function(){window.open('http://*****.com/***.html?url=
'+encodeURIComponent(window.location.href),'my_page_name',
'left=200,top=200,width=480,height=500,personalbar=0,
toolbar=0,scrollbars=1,resizable=1')})()
How can I make this like a modal window, meaning no ugly browser window borders - should I use jquery or something like in the bookmarklet URL and if so, how?
You could use the approach Firebug Lite uses.
Basically you insert an external JS file into your page when you click on the bookmark.
My bookmark
Just change BASE_URL, PATH_TO_JS and PATH_TO_ICON to what you need it to be.
Also, don't forget the "http://" in the BASE_URL, unless you want to use a relative path.
Your external JS file could contain a script which adds an element to the page which hovers over others. I recommend using the CSS in Twitter Bootstrap to figure out how to make a reliable modal window.
Edit --
To help you out I wrote a small demo. It consists of 2 files:
bookmark.html - adapted firebug code to create bookmark which adds script dynamically
bookmark.js - creates a modal with an iframe
bookmark.html
Bookmark
bookmark.js
(function() {
var script;
if(!window.jQuery) {
script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js";
document.body.appendChild(script);
}
(function check_if_loaded() {
if(!window.jQuery) {
setTimeout(check_if_loaded, 50);
} else {
(function($) {
var
$dark_bg = $('<div></div>').css({'z-index': '1000', 'background-color': '#000000', 'opacity': '0', 'position': 'absolute', 'width': '100%', 'height': '100%'}),
$iframe = $('<iframe></iframe>').css({'width': '100%', 'height': '100%', 'border': 1, 'overflow': 'hidden'}).prop({'src': 'http://bijtel.com/cv/', 'width': '100%', 'height': '100%', 'scrolling': 'no'}),
$close = $('<div></div>').css({'position': 'absolute', 'top': 0, 'right': 0, 'padding': '5px 10px', 'cursor': 'pointer', 'color': '#ffffff', 'font-size': '10pt', 'font-family': 'verdana'}).html('close ×');
$modal = $('<div></div>').css({'z-index': '1010', 'background-color': '#ffffff', 'opacity': '0', 'position': 'absolute', 'top': '10%', 'left': '10%', 'width': '80%', 'height': '80%', 'box-shadow': '7px 7px 5px #333'}).append($close, $iframe);
$('body').css({'padding': 0, 'margin': 0}).prepend($dark_bg, $modal);
$dark_bg.animate({'opacity':0.5}, 400);
$modal.animate({'opacity':1}, 400);
$close.on('click', function() {
$dark_bg.animate({'opacity': 0}, 400, function(){ $dark_bg.remove(); });
$modal.animate({'opacity': 0}, 400, function(){ $modal.remove(); });
});
}(window.jQuery));
}
}());
}());
Demo at: http://bijtel.com/stackoverflow/bookmark/
I don't know much about the subject, but looking at the delicious.com bookmarklet I noticed some parameters to limit which parts of the browser window will be shown:
(function() {
f = 'http://www.delicious.com/save?url=' + encodeURIComponent(window.location.href) + '&title=' + encodeURIComponent(document.title) + '&v=5&';
a = function() {
if (!window.open(f + 'noui=1&jump=doclose', 'deliciousuiv5', 'location=yes,links=no,scrollbars=no,toolbar=no,width=550,height=550')) location.href = f + 'jump=yes'
};
if (/Firefox/.test(navigator.userAgent)) {
setTimeout(a, 0)
} else {
a()
}
})()
The parameters I'm talking about are the location, links, scrollbars and toolbar. That does not make it modal, though, and I doubt there is a feature for that (I'm assuming browser windows are independent of each other). But they provide a "cleaner" window nonetheless...
Update: check out this link. Basically, what the bookmarklet does is to create a new script tag and append it to the body. I'm assuming you could do anything you want in that script, including create a jQuery dialog the way you wanted (in fact, this bookmarklet does use jQuery, but it's embedded in the script itself; see the source).
Here's the code. I wouldn't use this bookmarklet myself (since I'd have to provide my username/password in the clear), but it's a starting point for you to do yours:
var e = document.createElement('script');
e.setAttribute('language', 'javascript');
e.setAttribute('src', 'http://t.rc.vc/delicious/js/delicious.js?username=***&password=***');
e.setAttribute('id', 'delicious_submitter');
document.body.appendChild(e);
void(0);
Obs.: in both examples, I stripped the javascript: part and formatted the code for readability.

Jquery - Dynamic button, can I clean this up?

I created a button that will randomly appear on the screen (per my boss's request) that when clicked will open an email in order to provide feedback.
My goal is to make this script do everything, mainly so I don't have to access the ASP markup or CSS files for each website. Just throw the script in the header and place the image in the folder.
I created the script to:
Create a div that contains the button
set the CSS for the elements of that div (there will be a little image next to some text)
appear to the user at random
The script I came up with works fine, however, I was wondering if there was anyway I can clean this up at all. (I'm kind of new to writing my own Jquery scripts and I'm trying to learn how to be as organized as possible.)
Jquery:
$(function () {
var fbContainer = $('<div id="feedback"><img src="image.gif" /> Feedback</div>')
.css({
'display': 'none',
});
$('#header').append(fbContainer);
$('#feedback a').css({
'font-family': 'arial',
'float': 'left',
'text-decoration': 'none',
'color':'#000000'
});
$('#feedback img').css({
'float': 'left',
'margin': '3px 5px 0 0';
});
var randofactor = .5;
var randomizer = Math.random();
if (randomizer < randofactor) {
fbContainer.css('display', 'block');
}
});
Thanks for any assistance
You could try encapsulating your code inside a javascript object, which I would recommend placing inside a separate file. I would suggest moving the header where the button is placed to be parametrized inside a constructor function, so you can reuse it elsewhere.
Separating the various logical parts such as object creation and styling into their own functions also helps readability of your code.
<script type="text/javascript">
var randomFeedBackButton = {
getfbContainer: function (header,feedBackAddress) {
var fbContainer = $('<div id="feedback"><img src="image.gif" /> <a href=' + feedBackAddress + '>Feedback</a></div>')
.css({
'display': 'none'
});
header.append(fbContainer);
return fbContainer;
},
generateCss: function () {
$('#feedback a').css({
'font-family': 'arial',
'float': 'left',
'text-decoration': 'none',
'color': '#000000'
});
$('#feedback img').css({
'float': 'left',
'margin': '3px 5px 0 0'
});
},
initialize: function (header) {
var container = this.getfbContainer(header, "mailto:feedback#mywebaddress.com");
this.generateCss();
var randofactor = .5;
var randomizer = Math.random();
if (randomizer < randofactor) {
container.css('display', 'block');
}
}
};
$(function () {
randomFeedBackButton.initialize($('#header')); /*call your script*/
});
</script>

Categories