I am getting out of focus when I am practicing the oop and I don't know how to continue.
I have two code and I need to unite the both code.
I need to initialize the variable of svg by using the method of oop.
Need help.
Thanks.
link svg:
function ArrayMaker(svgcx, svgcy ,svgr ,svgstroke ,svgstroke_width ,svgfill ) {
this.svgcx = 100;
this.svgcy = 50;
this.svgr = 40;
this.svgstroke = "red";
this.svgstroke_width = 3;
this.svgfill = "yellow";
this.theArray = [ this, svgcx ,svgcy ,svgr ,svgstroke ,svgstroke_width ,svgfill ];
}
ArrayMaker.prototype = {
someMethod: function () {
alert( 'someMethod called');
},
getArray: function () {
return this.theArray;
}
};
var am = new ArrayMaker( 'one', 'two' );
var other = new ArrayMaker( 'first', 'second' );
alert(am.getArray());
this code is work:
var cx=100;
var cy=50;
var r=40;
var stroke="red";
var stroke_width=3;
var fill="yellow";
var htm = "<html>";
htm += "<head>";
htm += "<title>test3</title>";
htm += "</head>";
htm += "<body>";
htm += "<svg ";
htm += " version=";
htm += "\"1.1\"";
htm += ">";
htm += "<circle ";
htm += "cx="+cx+" ";
htm += "cy="+cy+" ";
htm += "r="+r+" ";
htm += "stroke="+stroke+" ";
htm += "stroke-width="+stroke_width+" ";
htm += "fill="+fill+" ";
htm += "/>";
htm += "</body>";
htm += "</html>";
document.write(htm);
To create SVG elements with JS you need to use createElementNS() and create elements with the SVG namespace (http://www.w3.org/1999/xhtml). For example, see this demo on my site: http://phrogz.net/SVG/svg_in_xhtml5.xhtml
var svgNS = "http://www.w3.org/1999/xhtml";
function createOn( root, name, attrs ){
var el = document.createElementNS(svgNS,name);
for (var attr in attrs){
if (attrs.hasOwnProperty(attr)) el.setAttribute(attr,attrs[attr]);
}
return root.appendChild(el);
}
var svg = createOn( document.body, 'svg', {viewBox:'-100 -100 200 200'} );
createOn( svg, 'circle', { cx:-60, cy:-50, r:20, fill:'#000' });
Note that SVG attributes are not in any namespace, so you can use setAttribute() (as I did above) or setAttributeNS(null,...). However, this is not true for attributes specified outside of SVG, like XLink's href. For such you need to create the attributes with the correct namespace.
You should move away from w3schools and document.write. They both represent old ways of doing things.
Phrogz answered before me, but I'll post a link to a jsFiddle you can play with anyway.
http://jsfiddle.net/ctrlfrk/nnjsw/
The code in that link will show you how to properly create a 'circle' object, and how to add a method to the prototype (in this case to move the circles)
Related
BACKBONE and Jquery
I have a piece of code:
var ChatMessage = Backbone.View.extend({
el : '#friend-list',
events : {},
initialize : function() {},
loadMessage : function(parent_id) {
//ukrycie komunikatów etc.
$("#chat_body").html('');
$("#end-record-info").hide();
$("#end-record-load").hide();
page = 1;
this.ajax(parent_id,page); //initial data load
},
ajax : function(parent_id,page) {
$.getJSON( "/**/**/"+parent_id+"/"+page, function( json ) {
$("#end-record-load").hide();
this.build(json.message, page);
page ++; //page increment
loading = false; //set loading flag off
end_record = false;
if(json.max < page){ //no more records
end_record = true; //set end record flag on
return; //exit
}
});
},
build : function(arr, page) {
alert('dgd');
html = '';
var height = 0;
arr.reverse();
$.each(arr, function(i, data){
html += '<div class="answer '+data.side+'">';
html += '<div class="avatar">';
html += '<a href="**" target="_blank">';
html += ''+data.id+'';
html += '</a>';
html += '<div class="status offline"></div>';
html += '</div>';
html += '<div class="name">';
html += '<a href="**" target="_blank">';
html += data.username;
html += '</a>';
html += '</div>';
html += '<div class="text">';
html += data.content;
html += '</div>';
html += '<div class="time">';
if (data.side != 'left') {
html += data.dateSendMessage
}
else {
if (data.read == 0) {
html += 'xxx';
}
else {
html += 'xxx';
}
}
html += '</div>';
html += '</div>';
});
var nh = $('#chat_body').html();
$('#chat_body').html(html+nh);
if (page == 1) {
$('#chat_body .answer').each(function(i, value){
height += parseInt($(this).height());
});
height += '';
$('.chat2').scrollTop(height);
}
}
});
In AJAX method I want to build method
this.build(json.message, page);
But something does not work and I get an error.
pm2.js:67TypeError: this.build is not a function. (In 'this.build(json.message, page)', 'this.build' is undefined)
Can anyone help? What changes in this piece of code can be by the way?
Piotr
You should probably save current context before calling getJSON:
ajax : function(parent_id,page) {
var self = this;
$.getJSON( "/**/**/"+parent_id+"/"+page, function( json ) {
...
self.build(json.message, page);
I want to create separate backgrounds for each letter in the site-description span within the header on the Wordpress responsive theme.
I have added a function in functions.php
<?php
/**
* Setup Responsive Child Theme Functions
*/
function site_description_spans() {
echo 'Text within header'; // Replace this line with code from `https://stackoverflow.com/questions/17517816/color-every-character-differently
}
add_action( 'responsive_in_header', 'site_description_spans' );
?>
This successfully targets within the header within the responsive theme
But then I tried to add the following code within this function from another Stack Exchange post by replacing the
echo 'text within header' //above
The link to the javascript function on stack exchange is here
Color every character differently
and the relevant code is
$('.site-description').find('span').each(function(){
var $el = $(this),
text = $el.text(),
len = text.length,
newCont = '';
for(var i=0; i<len; i++){
var bgColor= '#'+ (Math.random() * 0xffffff).toString(16).substr(-6);
newCont += '<span style="background:'+bgColor+'">'+ text.charAt(i) +'</span>';
}
$el.html(newCont);
});
And it doesn't seem to work. Would be grateful for any suggestions.
Now i'm not too sure on the outputted HTML but i'm going to take a wild guess, that this is how the HTML is being output:
<span class="site-description">
Text within header
</span>
What you need if the code is to work as expected
<div class="site-description">
<span>
Text within header
</span>
</div>
Option 1 - Change HTML
Change your HTML code so that a span is contained within a div and the function to add the text is within the span
Something like this
<div class="site-description">
<span>
<!-- RUN FUNCTION HERE -->
</span>
</div>
Option 2 - Change jQuery
Change your jQuery function to something like this:
$('.site-description').each(function() {
var $el = $(this),
text = $el.text(),
len = text.length,
newCont = '';
for (var i = 0; i < len; i++) {
var bgColor = '#' + (Math.random() * 0xffffff).toString(16).substr(-6);
newCont += '<span style="background:' + bgColor + '">' + text.charAt(i) + '</span>';
}
$el.html(newCont);
});
Or generally just fix the first part of the query so that it finds the correct class or element.
Ok,
I have tried option 2 and just inserted it in the original function but I am not really sure what I am doing here. I understand what you suggested in option 2 and it looks like that would work, I am just not sure how to add it as a function in functions.php
This is what I have
function site_description_spans() {
$('.site-description').each(function() {
var $el = $(this),
text = $el.text(),
len = text.length,
newCont = '';
for (var i = 0; i < len; i++) {
var bgColor = '#' + (Math.random() * 0xffffff).toString(16).substr(-6);
newCont += '<span style="background:' + bgColor + '">' + text.charAt(i) + '</span>';
}
$el.html(newCont);
});
}
add_action( 'responsive_in_header', 'site_description_spans' );
?>
Trouble is that I get the following error with it
Parse error: syntax error, unexpected '(', expecting T_VARIABLE or '$' in /***/*****/public_html/*****/dev/wp-content/themes/responsive_child/functions.php on line 11
My Problem:
document.getElementById("values").innerHTML does not write anything. If I try to do document.getElementById("values").innerHTML = "stuff"; (just with a String) - nothing happens.
What am I doing wrong here?
HTML:
<form onsubmit="save_entry();return false;">
<label for="i_km">Kilometer: <input type="text" name="km" id="i_km"></label><br>
<label for="i_fuel">Sprit: <input type="text" name="fuel" id="i_fuel"></label><br>
<input type="submit" value="Save" />
</form>
<div id="values"></div>
JavaScript:
function save_entry() {
var anzahl = localStorage.length/2;
var nameKeyKm = "k" + anzahl;
localStorage.setItem(nameKeyKm,document.forms[0]["km"].value);
var nameKeyF = "F" + anzahl;
localStorage.setItem(nameKeyF,document.forms[0]["fuel"].value);
document.write("Entry saved!")
}
function show_entry() {
document.getElementById("values").innerHTML = "<table><th>Kilometers</th><th>Tanked</th>";
for (var i = 0; i < localStorage.length/2; i++) {
alert("d");
var temp_km = "k"+i;
var temp_f = "F"+i;
document.getElementById("values").innerHTML = "<tr>";
document.getElementById("values").innerHTML = "<td>"+localStorage.getItem(temp_km)+"</td>";
document.getElementById("values").innerHTML = "<td>"+localStorage.getItem(temp_f)+"</td>";
document.getElementById("values").innerHTML = "</tr>";
}
document.getElementById("values").innerHTML = "</table>";
}
show_entry();
This does work!
function show_entry(){
var content = '';
content = content + '<table><th>Kilometer</th><th>Getankt</th>';
for(var i = 0; i < localStorage.length/2; i++)
{
var temp_km = "k"+i;
var temp_f = "F"+i;
content = content + "<tr>";
content = content + "<td>"+localStorage.getItem(temp_km)+"</td>";
content = content + "<td>"+localStorage.getItem(temp_f)+"</td>";
content = content + "</tr>";
}
content = content + "</table>";
document.getElementById("values").innerHTML = content;
}
innherHTML is an attribute, so everytime you write document.getElementById('id').innerHTML = '...' you are actually changing the value of innerHTML to that thing, not concatenating it.
So writing document.getElementById("values").innerHTML = "<table><th>Kilometers</th><th>Tanked</th>"' changes the value of innerHTML to "<table><th>Kilometers</th><th>Tanked</th>"', and, afterwards, you replaced this value for <tr>, then for <td>...</td> and so on...
You clearly want to create a table. Therefore, you should be concatenating the strings, using +=, like this:
function show_entry() {
document
.getElementById("values")
.innerHTML = "<table><th>Kilometers</th><th>Tanked</th>";
for(var i = 0; i < localStorage.length/2; i++)
{
var temp_km = "k"+i;
var temp_f = "F"+i;
document.getElementById("values").innerHTML += "<tr>";
document.getElementById("values").innerHTML += "<td>"+localStorage.getItem(temp_km)+"</td>";
document.getElementById("values").innerHTML += "<td>"+localStorage.getItem(temp_f)+"</td>";
document.getElementById("values").innerHTML += "</tr>";
}
document.getElementById("values").innerHTML += "</table>";
}
show_entry();
Each time you do
document.getElementById("values").innerHTML = "...";
you will replace the html inside the div with ID 'values'
So calling it multiple times with different values doesn't make sense.
You would either call it once and setting the whole innerHTML at once, like this
document.getElementById("values").innerHTML = "<tr><td>....etc...</td></tr>";
If you would call innerHTML sequentially you would do it as follows (which is just how to append any string in javascript), but in the comments below I just learned this should not be done like this:
document.getElementById("values").innerHTML += "<tr>";
document.getElementById("values").innerHTML += "<td>"+localStorage.getItem(temp_km)+"</td>";
document.getElementById("values").innerHTML += "<td>"+localStorage.getItem(temp_f)+"</td>";
document.getElementById("values").innerHTML += "</tr>";
For my site I want to have a little chat / support field. At the moment I can write and also save it right to the database.
But I want to have it, that if I open the site again the old text come from the database. But how is the best way to do that? I also think my Array is false, because I only get one and not all data back from the database.
My javascript testcode:
initChat: function () {
var cont = $('#chats');
var list = $('.chats', cont);
var form = $('.chat-form', cont);
var input = $('input', form);
var btn = $('.btn', form);
var handleClick = function (e) {
e.preventDefault();
var text = input.val();
if (text.length == 0) {
return;
}
var time = new Date();
var time_str = time.toString('dd.MM.yyyy - H:mm')+ " Uhr";
var tpl = '';
tpl += '<li class="out">';
tpl += '<img class="avatar" alt="" src="assets/img/avatar.png"/>';
tpl += '<div class="message">';
tpl += '<span class="arrow"></span>';
tpl += 'Meine Frage ';
tpl += '<span class="datetime">vom ' + time_str + '</span>';
tpl += '<span class="body">';
tpl += text;
tpl += '</span>';
tpl += '</div>';
tpl += '</li>';
var msg = list.append(tpl);
var time_str_new = time.toString('yyyy-MM-dd H:mm:ss');
$.ajax({
type: "POST",
url: '../support.php',
data: {datum: time_str_new, text: text},
dataType: 'json',
success: function(data)
{
input.val("");
}
});
$('.scroller', cont).slimScroll({
scrollTo: list.height()
});
}
My php testscript:
$kundenid = KUNDENID;
$query = "INSERT INTO support set datum = '$datum', kunde = '$kundenid', text = '$text', typ = 'kunde'";
$result = mysql_query($query,$db);
$querysup = "SELECT id, datum, kunde, text, typ FROM support WHERE kunde = '$kundenid'";
$resultsup = mysql_query($querysup,$db);
while($rowsup = mysql_fetch_array($resultsup)) {
$datum = $rowsup['datum'];
$text = $rowsup['text'];
$typ = $rowsup['typ'];
$data = array("datum"=>$rowsup['datum'], "text"=>$rowsup['text'], "typ"=>$rowsup['typ']);
}
echo json_encode($data);
Ok now I have this code. If I post a new text it show me all posts from database. But I need it that the data from mysql still there before my first post.
initChat: function () {
var cont = $('#chats');
var list = $('.chats', cont);
var form = $('.chat-form', cont);
var input = $('input', form);
var btn = $('.btn', form);
var handleClick = function (e) {
e.preventDefault();
var text = input.val();
if (text.length == 0) {
return;
}
var time = new Date();
var time_str = time.toString('dd.MM.yyyy - H:mm')+ " Uhr";
var tpl = '';
tpl += '<li class="out">';
tpl += '<img class="avatar" alt="" src="assets/img/avatar.png"/>';
tpl += '<div class="message">';
tpl += '<span class="arrow"></span>';
tpl += 'Meine Frage ';
tpl += '<span class="datetime">vom ' + time_str + '</span>';
tpl += '<span class="body">';
tpl += text;
tpl += '</span>';
tpl += '</div>';
tpl += '</li>';
var msg = list.append(tpl);
var time_str_new = time.toString('yyyy-MM-dd H:mm:ss');
$.ajax({
type: "POST",
url: 'support.php',
data: {datum: time_str_new, text: text},
dataType: 'json',
success: function(data)
{
var myArray = data;
for (var i = 0; i < myArray.length; i++) {
var datum = new Date(myArray[i].datum);
var tpl = '';
tpl += '<li class="out">';
tpl += '<img class="avatar" alt="" src="assets/img/avatar.png"/>';
tpl += '<div class="message">';
tpl += '<span class="arrow"></span>';
tpl += 'Meine Frage ';
tpl += '<span class="datetime">vom ' + datum.toString('dd.MM.yyyy - H:mm:ss')+ ' Uhr' + '</span>';
tpl += '<span class="body">';
tpl += myArray[i].text;
tpl += '</span>';
tpl += '</div>';
tpl += '</li>';
var msg = list.append(tpl);
}
}
});
But how to load it from the array to my javascript... so if I refresh the page the values from array are in my "Chatbox"
The missing part could be a simple "assign" operation like
var chatArr=<?PHP echo json_encode($data) ?>;
in a <script type="language/JavaScript"> section, which you can insert after you have dealt with all the PHP stuff in the document. You should make sure of course that nothing "unwanted" gets into $data. After that you can do whatever you want to do with the JavaScript Array/Object in a $(function(){...}) section anywhere else in the document.
There are of course also dedicated JSON parsers which will also take care of Date objects. The simple assign will only generate Stings or numeric contents in the JavaScript object, see here.
When i click a link, JS adds a new file tag to the page but every time it reloads all the file tags. What i need is that when i click on a link, it should append a file tag without re-loading earlier file tags.
Please suggest if any one has an idea about this.
Following is my code.
var intTextBox = 0;
function addElement()
{
intTextBox = intTextBox + 1;
var contentID = document.getElementById('content');
contentID.innerHTML = "";
var howManyTextBoxes = intTextBox;
for ( var i = 0; i < howManyTextBoxes; i++)
{
var newTBDiv = document.createElement('div');
newTBDiv.setAttribute('id', 'strText' + intTextBox);
newTBDiv.innerHTML += "<input type=file name='fileUpload' size='40'/>";
contentID.appendChild(newTBDiv);
}
and this is how i call to JS function.
Attach more files
You should return false from that function, otherwise the link reloads the page:
function addElement() {
intTextBox = intTextBox + 1;
var contentID = document.getElementById('content');
contentID.innerHTML = "";
var howManyTextBoxes = intTextBox;
for ( var i = 0; i < howManyTextBoxes; i++) {
var newTBDiv = document.createElement('div');
newTBDiv.setAttribute('id', 'strText' + intTextBox);
newTBDiv.innerHTML += "<input type=file name='fileUpload' size='40'/>"; contentID.appendChild(newTBDiv);
return false;
}
You can call like this :
Attach more files
do not forget the return false;