jeudi 13 août 2015

If argument is blank do not append to string

I want to write a simple javascript function to append to a string of values given arguments, but only if the arguments have values. Here is an example:

function foo(bar){
  return "hello" + bar;  
}

If I run foo() I will get "helloundefined" I want it to just return "hello" and if i run foo('world') that works right now with "helloworld"

I was thinking I could do something like:

return "hello" + null || bar but i would just get "hellonull"

or

return "hello" + if(bar){bar} is invalid syntax.



via Chebli Mohamed

Blanket.js code is instrumented, but will not display when running with Mocha and chai and AMD RequireJS

I've google and SO'd extensively for the answer, and have a found a number of repositories and tutorials with something that wasn't quite what I was looking for, but I attempted to adapt anyway.

According to earlier issues I've looked through, the key to Blanket.js' coverage working is that window._$blanket is defined, and mine is, along with the instrumentations of my source.

However, when my testrunner.html loads, it tends to alternate between a full fledged blanket.js report, or the actual mocha tests (with checkmarks and css and whatnot). I'm inclined to think it has to do with the source being asynchronously loaded with RequireJS.

Here's my testRunner.html:

<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="/js/vendor/npm/mocha/mocha.css" />
    <script type="text/javascript" src="js/vendor/mocha/mocha.js"></script>
    <script type="text/javascript" src="js/vendor/require.js"></script>
    <script type="text/javascript" src="/js/test/unit/config.js"></script>
    <script type="text/javascript" src="/js/main.js"></script>
</head>
<body>
<script type="text/javascript" data-cover-only="/js/test/unit/js/some/path/to/"
        src="http://ift.tt/1Wnooca">
</script>
<script type="text/javascript" src="/js/vendor/blanket/src/adapters/mocha-blanket.js"></script>
<script>

    require(['mocha', 'chai', 'chai-jquery', 'sinon'], function(mocha, chai, chaiJquery, sinon) {

        // Init Chai
        chai.should(); //initializes chai.should()
        chai.use(chaiJquery);
        expect = chai.expect;

        mocha.setup({
            ui: 'bdd',
            ignoreLeaks: true
        });

        require([
            '../js/test/unit/js/some/path/to/AModel.test.js',
            '../js/test/unit/js/some/path/to/SModel.test.js',
        ], function(require) {
            mocha.run();
        });
    });
</script>
<div id="mocha"></div>
</body>
</html>

and here's the somemodel.test.js file:

define([
        "app",
        "moment",
        "util/utils",
    ],
    function(app) {

        describe('AModel', function() {

            beforeEach(function () {
                this.AModel = new AModel ({
                    type: undefined,
                    name: undefined, 
                });

                sinon.stub(this.AModel, 'fetch').yieldsTo('success', {
                    fun: "funk"
                });
            });

            afterEach(function () {
                this.AModel = null;
            });




            it('should get a node returned from a given ID', function() {
                var that = this;
                var nodeModel = this.AModel.getNode("node1");
                expect(nodeModel instanceof SModel).to.be.true;
            });

            it('should get the peer nodes of an object', function() {
                var temp = this.AModel.getPeerNodes("node1", "fakeType" );
                expect(temp).to.have.length(10);
            });


        });
    }
);



via Chebli Mohamed

wait for css_parser.getCSSFiles()

I want to render page when CSS will be loaded. Function css_parser.getCSSFiles() reads file asynchronously and sends CSS content to variable css.cssFile . How I can force res.render to wait for end of file reading?

router.get('/main', function(req, res) {

    css_parser.getCSSFiles();
    app.locals.css = css.cssFile;

    res.render('ua', {
        css: app.locals.css,
    });

});

UPDATE: So basically, I want to read also other kind of files. getJSFile is similar to getCSSFiles and I also initialize it before res.render

getJSFile: function(directory, file, variable) {
    fs.readFile(directory + file, 'utf8', function(err, data) {
        if (err) {
            return console.log(err);
        }
        variable.push(data);
});



via Chebli Mohamed

How to pass Javascript date object (formatted datetime) from Laravel API

My Laravel 5 API pulls regular datetime columns from my MySQL db. My JSON datetime output looks like this:

2015-08-13 13:45:00

but the widget reading my JSON expects a JavaScript Date Object? What would be the syntax to pass my datetime as a JavaScript Date Object?

My current Laravel method looks like so:

public function transform($events)
{
    return [
        'startdt' => $events['event_start'],
        'enddt'   => $events['event_end'],
    ];
}

This is the code I have in my widget JS file:

'use strict';

angular
  .module('demo', ['mwl.calendar', 'ui.bootstrap', 'ngTouch', 'ngAnimate'])
  .controller('MainCtrl', function ($modal, moment, $http) {

var vm = this;
vm.calendarView = 'month';
vm.calendarDay = new Date();

$http.get('http://ift.tt/1Wnooc0').success(function(events) {    
    vm.events = events.events;
}); 



via Chebli Mohamed

Handsontable dropdowns with multiple selections

I am trying to extend the handsontable plugin to support multiple selections in its dropdown list. I have already tried extending the base Editor built into the library by modifying the 'dropdownEditor' as suggested http://ift.tt/1IPeF4Y. I spent hours reading and searching through the source for keywords but I am not coming up with anything of real use.

I do not mind if this is answered using the Angular extension or another native ECMA5 or 6 way of extending the http://ift.tt/1FAcz8U plugin.

So far my only thoughts were to actually extend the framework with this bit of code following the patterns that exist. I added all LOC below that are pointing to: multiselect or Handsontable.MultiselectDropdownCell copied the dropdown method, called the new name and everything works, however still cannot see where I could begin to find what I am looking for.

Handsontable.MultiselectDropdownCell ={
  editor: getEditorConstructor('multiselectdropdown'),
  renderer: getRenderer('autocomplete')
};

Handsontable.cellTypes = {
  text: Handsontable.TextCell,
  date: Handsontable.DateCell,
  numeric: Handsontable.NumericCell,
  checkbox: Handsontable.CheckboxCell,
  autocomplete: Handsontable.AutocompleteCell,
  handsontable: Handsontable.HandsontableCell,
  password: Handsontable.PasswordCell,
  dropdown: Handsontable.DropdownCell,
  multiselect: Handsontable.MultiselectDropdownCell
};

Handsontable.cellLookup = { validator: {
    numeric: Handsontable.NumericValidator,
    autocomplete: Handsontable.AutocompleteValidator
}};

I have at a modified version of dropdown editor in place that looks like:

import {getEditor, registerEditor} from './../editors.js';
import {AutocompleteEditor} from './autocompleteEditor.js';

/**
 * @private
 * @editor MultiSelectDropdownEditor
 * @class MultiSelectDropdownEditor
 * @dependencies AutocompleteEditor
 */
class MultiSelectDropdownEditor extends AutocompleteEditor {
  prepare(row, col, prop, td, originalValue, cellProperties) {
    super.prepare(row, col, prop, td, originalValue, cellProperties);
    this.cellProperties.filter = false;
    this.cellProperties.strict = true;
  }
}

export {MultiSelectDropdownEditor};

registerEditor('multiselectdropdown', MultiSelectDropdownEditor);

At this point I have no clue where the click event is happening when the user selects an item from the dropdown list. Debugging has been painful for me because it is through Traceur. I tried setting a click event after the module is ready and the DOM is as well however I cannot get even an alert to fire based off of a click on one of the select dropdown cells. The 'normal' cells I can get a click with a simple:

$('body').on('click','#handsontable td', someAlert)

However not so for the menu contents. Right clicking to inspect the dropdown menu means first disabling the context menu like the one on http://ift.tt/WWRahK. Then you will notice that right clicking to inspect anything will fire an event that closes the dropdown menu you are trying to inspect.

I've put breakpoints all through the libraries source code, I cannot figure this one out.

The only thing I want to do is figure out where the part of the code that highlights the menu item and sets it to an active selection, turn that into a method that accepts multiple selections (up to the entire array of options available, clicking an active item will disable it lets just say).

Then ensuring that those selections are actually in the Handsontable 'data scope'.

Thats it, I don't need it to even render in the cell what things have been chosen, although any help there would be great because unfortunately, I am yet to find the spot when the options in the dropdown are rendered either.

I have also tried using the Select2Editor made for handsontable as seen http://ift.tt/1WnonVE and http://ift.tt/1IPeGWt , however it does not help my cause much. Here is what the dropdown cell in handsontable looks like:

http://ift.tt/1WnoobS

Finally, heres a fiddle: http://ift.tt/1IPeF54

I would be super appreciative if someone could help me out here. Thanks SO!

UPDATE

I have managed to parse the values in the cell and turn the type into an array containing the values (so typing red blue will turn an array containing ['red','blue']) . I have run this array through the internal sort algorithm which parses the options and returns an index of a matching item. I get this working fine and I now am passing the array into the highlight method. This method passes the values the the core library WalkOnTable. I do not see where I can alter the logic to select more than one value instead of unhighlighting the first option.

 this.selectCell = function(row, col, endRow, endCol, scrollToCell, changeListener) {
var coords;
changeListener = typeof changeListener === 'undefined' || changeListener === true;
if (typeof row !== 'number' && !Array.isArray(row) || row < 0 || row >= instance.countRows()) {
  return false;
}
if (typeof col !== 'number' || col < 0 || col >= instance.countCols()) {
  return false;
}
if (typeof endRow !== 'undefined') {
  if (typeof endRow !== 'number' || endRow < 0 || endRow >= instance.countRows()) {
    return false;
  }
  if (typeof endCol !== 'number' || endCol < 0 || endCol >= instance.countCols()) {
    return false;
  }
}
// Normal number value, one item typed in
if (!Array.isArray(row) && typeof row === 'number'){
  coords = new WalkontableCellCoords(row, col);

  walkSelection(coords);
}

This is the spot where I think I need WalkontableCellCoords to be modified to accept an array and then highlight and select both values when the dropdown is opened and closed. I also need to be able to select multiple options via touch or click event.

else {
  // Array found, apply to each value
  new WalkontableCellCoords(row[0], col);
  new WalkontableCellCoords(row[1], col);
}

function walkSelection(coords){
  priv.selRange = new WalkontableCellRange(coords, coords, coords);
  if (document.activeElement && document.activeElement !== document.documentElement && document.activeElement !== document.body) {
    document.activeElement.blur();
  }
  if (changeListener) {
    instance.listen();
  }
  if (typeof endRow === 'undefined') {
    selection.setRangeEnd(priv.selRange.from, scrollToCell);
  } else {
    selection.setRangeEnd(new WalkontableCellCoords(endRow, endCol), scrollToCell);
  }
  instance.selection.finish();
}

return true;

};



via Chebli Mohamed

Nodejs - close socket event reason

Based on the documentation for net module it says that:

Emitted once the socket is fully closed. The argument had_error is a boolean which says if the socket was closed due to a transmission error.

Also, we know that close event will be triggered after error event always:

Emitted when an error occurs. The 'close' event will be called directly following this event.

I have a few doubts regarding how closing of socket works (more precisely when it can happen). I would like to conclude within the script when "close" event is triggered, which side closed the socket. So if "close" event is triggered on client side does this 100% means that socket is closed by other side (and vice versa)? Or I am missing something?

Is it possible for socket to encounter some kind of error which will trigger "close" event even other side is still running? If that is the case how can i conclude from where (and because of what kind of reason) socket is closed? Is it possible to conclude which one of two sides closed the socket (server or client)?



via Chebli Mohamed

Sequelize.js One-to-Many relationship foreign key

I am creating a survey app using Node.js/Express and MySQL with Sequelize.js ORM.

I am having trouble setting the relationship between the 2 models correctly. I'd like to have the Questions' qId foreign key in the Answers Table.

// define the Questions table
var Questions = sequelize.define('Questions', {
  qId: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true},
  question: Sequelize.STRING
}, {
  timestamps: false
});

// define the Answers table
var Answers = sequelize.define('Answers', {
  aId: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true},
  answer: Sequelize.STRING,
  answer_count: { type: Sequelize.INTEGER, defaultValue: 0}
}, {
  timestamps: false
});

// define one-to-many relationship
Questions.hasMany(Answers, {as: 'Answers', foreignKey: 'qId'});

Questions.sync({force: true}).then(function() {
  // OPTIONAL: create a new question upon instantiating the db using sequelize
  Questions.create({question: 'what is your language?'});
  Questions.create({question: 'what is your drink?'});
  console.log('created Questions table');
  }).catch(function(error) {
    console.log('error creating Questions table');
  });

Answers.sync({force: true}).then(function() {
  Answers.create({answer: 'python', qId: 1});
  Answers.create({answer: 'javascript', qId: 1});
  Answers.create({answer: 'ruby', qId: 1});
  Answers.create({answer: 'c++', qId: 1});
  Answers.create({answer: 'manhattan', qId: 2});
  Answers.create({answer: 'cosmopolitan', qId: 2});
  console.log('created Answers table');
}).catch(function(error) {
  console.log('error creating Answers table');
});

But when I do MySQL queries:

select * from Questions, Answers where Answers.qId=2;

it's showing the following:

mysql> select * from Answers;
+-----+--------------+--------------+------+
| aId | answer       | answer_count | qId  |
+-----+--------------+--------------+------+
|   1 | python       |            0 |    1 |
|   2 | javascript   |            0 |    1 |
|   3 | ruby         |            0 |    1 |
|   4 | c++          |            0 |    1 |
|   5 | manhattan    |            0 |    2 |
|   6 | cosmopolitan |            0 |    2 |
+-----+--------------+--------------+------+
6 rows in set (0.00 sec)

mysql> select * from Questions;
+-----+------------------------+
| qId | question               |
+-----+------------------------+
|   1 | what is your language? |
|   2 | what is your drink?    |
+-----+------------------------+
2 rows in set (0.00 sec)

mysql> select * from Questions, Answers where Answers.qId=2;
+-----+------------------------+-----+--------------+--------------+------+
| qId | question               | aId | answer       | answer_count | qId  |
+-----+------------------------+-----+--------------+--------------+------+
|   1 | what is your language? |   5 | manhattan    |            0 |    2 |
|   1 | what is your language? |   6 | cosmopolitan |            0 |    2 |
|   2 | what is your drink?    |   5 | manhattan    |            0 |    2 |
|   2 | what is your drink?    |   6 | cosmopolitan |            0 |    2 |
+-----+------------------------+-----+--------------+--------------+------+

When I'd like it to show

mysql> select * from Questions, Answers where Answers.qId=2;
+-----+------------------------+-----+--------------+--------------+------+
| qId | question               | aId | answer       | answer_count | qId  |
+-----+------------------------+-----+--------------+--------------+------+ 
|   2 | what is your drink?    |   5 | manhattan    |            0 |    2 |
|   2 | what is your drink?    |   6 | cosmopolitan |            0 |    2 |
+-----+------------------------+-----+--------------+--------------+------+

I've been looking at the documentation for a few hours now and any help would be much appreciated :) Thank you.



via Chebli Mohamed

How can I return data from `$http` with a $q resolve?

I have a javascript function which for this question I have simplified. It actually does some things to the data retrieved from the $http call and then I want that data to be made available along with a promise to the function that called it:

getTopics = (queryString: string) => {
        var self = this;
        var defer = self.$q.defer();
        self.$http({
            // cache: true,
            url: self.ac.dataServer + '/api/Topic/GetMapData' + queryString,
            method: "GET"
        })
            .success((data) => {

                var output: ITopics = {
                    details: data
                }
                // output is correctly populated with data
                defer.resolve(output);

                // I also tried this and it get seen in the calling function either
                // defer.resolve('abc');
            })
        return defer.promise;
    };

This calls it:

return topicService.getTopics("/" + subjectService.subject.id)
       .then((data) => {
           // data seems to be not defined
           var x = data;
});

Can someone tell me what I might be doing wrong. I thought the resolve would return data also but it seems not to be doing so.



via Chebli Mohamed

Getting Uncaught TypeError: Cannot read property 'get' of undefined in spite of the conditionals

I'm trying to retrieve images on Facebook Parse SDK, and I can't because of this error. And I don't know what i'm doing wrong because I use a conditional in order to no not to create a new variable if this is empty or undefined. This is the code (the console log points the error in the line where i'm creating the var ImageFl):

var Encharcamientos1 = Parse.Object.extend("Report");
var query = new Parse.Query(Inundaciones1);
query.equalTo("Tipo_Reporte", "Encharcamientos");
query.find({


success: function(results) {
    // Do something with the returned Parse.Object values

for (var i = 0; i < results.length; i++) {
if (!object.get('ImageFile') || object.get('ImageFile') !== '' || typeof object.get('ImageFile') !== 'undefined') {
var imageFl = object.get('ImageFile');
var imageURL = imageFl.url();
$('.imagen')[0].src = imageURL;
}

    var object = results[i];
     L.marker([object.get('Latitud'),object.get('Longitud') ], {icon: EncharcamientosIcon}).bindPopup(' <p><span class="grande"> ' + object.get('Tipo_Reporte') + ' </span></p><p>Fecha: ' + object.get('Fecha') + ' </p><p>Hora: ' + object.get('Hora') + '<div class="imagen"></div>' + '</p><p>Comentarios:<br /> ' + noundefined(object.get('Comentario')) + '</p>').addTo(Encharcamientos).addTo(todos);
    }
  },
  error: function(error) {
    alert("Error: " + error.code + " " + error.message);
  }
});



via Chebli Mohamed

Query Inside Parse Cloud For Loop

I have been trying to run my Parse Cloud Code for some time and can not seem to get around this problem:

I have an array of Parse objectId's called IDArray. I then am sending the array as a parameter of a PFCloud call. Once the array has been sent to the Cloud Code, I can not seem to successfully create a for loop that goes through and updates a number value stored as "points" on Parse for each objectId.

In a nutshell, this is all I am trying to accomplish:

  • I just need to be able to have the for loop go through each objectId and perform an action for each ID.

I have been trying to get this to work for some time but have had no luck. Here is the code that I have been trying to manipulate - hopefully it will give someone a starting point to answer my question.

Parse.Cloud.define('updateAllUsers', function(request, response) {
    var UserData = Parse.Object.extend('UserData');
    var query = new Parse.Query(UserData);
    var list = request.params.listID;
    var currentuser = request.params.user;

                   
    for (var i = 0; i < list.length; i++) {
                   
        var userdata = list[i];
                   
        query.get(list[i], {
                                       
            success: function(userdata) {
                                       
                response.success('Should add up');
                userdata.increment('Done', +1);
                userdata.save();
            },
            error: function() {
                response.error('something went wrong ' );
            }
        });
    }
});

If someone could please help me with this I would be very grateful. Thank you



via Chebli Mohamed

How to obtain only the integer part of a long floating precision number with JS?

I know there's

  • Math.floor
  • parseInt

But about this case:

Math.floor(1.99999999999999999999999999)

returning 2, how could I obtain only its integer part, equals to 1?



via Chebli Mohamed

Javascript generate all numbers between 2 numbers

Well I searched up a lot about this but couldn't find anything with decent documentation on how it works If someone would please explain with an example how to do this that would be great



via Chebli Mohamed

ECMAScript 2015: const in for loops

Which of the two (or neither/ both) code fragments below should be working in a complete ECMAScript 2015 implementation:

for (const e of a)

for (const i = 0; i < a.length; i += 1)

From my understanding, the first example should work because e is initialized for each iteration. Shouldn't this also be the case for i in the second version?

I'm confused because existing implementations (Babel, IE, Firefox, Chrome, ESLint) do not seem to be consistent and have a complete implementation of const, with various behaviours of the two loop variants; I'm also not able to find a concrete point in the standard, so that would be much appreciated.



via Chebli Mohamed

Karma+RequireJS: There is no timestamp, empty test suite. Why do I need to specify this file?

I am having an issue running my unit tests with Karma and its interaction with RequireJS.

I get this error:

'There is no timestamp for /base/bower_components/web/app/services/FooFactoryService.js!' Empty test suite.

As I understand, I must set this to NOT be included, so RequireJS can include it itself manually. My issue is that I have to specify exactly this file to get the tests running again. Wildcards and upper folders do not work, so far as I can see.

Here are my files in karma.conf.js - This one WORKS. As soon as I touch the first pattern, it breaks.

files:
    [
        ...

        {pattern: 'bower_components/**/**/**/FooFactoryService.js', included: false},

        {pattern: 'bower_components/**/*.js', included: false},
        {pattern: 'bower_components/**/*.json', included: false},
        {pattern: 'bower_components/**/*.html', included: false},

        ...
    ],

This works. But if I put a * in place of FooFactoryService.js, or just remove the line entirely and count on 'bower_components/**/*.js', I get the empty test suite error. If I move the line down beneath those three lines, it also fails. It needs to be above them, and it needs to specify the file.

Why does it require me to specify this exact file? Why do wildcards not hit it?



via Chebli Mohamed

Java Script Calculating and Displaying Idle Time

I'm trying to write with javascript and html how to display the time a user is idle (not moving mouse or pressing keys). While the program can detect mousemovements and key presses, the program for some reason isn't calling the idleTime() method which displays the time in minutes and seconds.

I'm wondering why the method isn't getting called, as if it is called it would display true or false if a button is pressed.

var startIdle = new Date().getTime();
var mouseMoved = false;
var buttonPressed = false;

function idleTime() {
  document.write(buttonPressed);
  if (mouseMoved || buttonPressed) {
  startIdle = new Date().getTime();
  }
  document.getElementById('idle').innerHTML =   calculateMin(startIdle) + " minutes: " + calculateSec(startIdle)   + " seconds";
  var t = setTimeout(function() {
  idleTime()
  }, 500);
}

function calculateSec(startIdle1) {
  var currentIdle = new Date().getTime();
  var timeDiff = Math.abs(currentIdle - startIdle1);
  var idleSec = Math.ceil(timeDiff / (1000));
  return idleSec % 60;
}

function calculateMin(startIdle1) {
  var currentIdle = new Date().getTime();
  var timeDiff = Math.abs(currentIdle - startIdle1);
  var idleMin = Math.ceil(timeDiff / (1000 * 60));
  return idleMin;
}

var timer;

// mousemove code
var stoppedElement = document.getElementById("stopped");

function mouseStopped() { // the actual function that is called
   mouseMoved = false;
   stoppedElement.innerHTML = "Mouse stopped";
}

window.addEventListener("mousemove", function() {
   mouseMoved = true;
   stoppedElement.innerHTML = "Mouse moving";
   clearTimeout(timer);
   timer = setTimeout(mouseStopped, 300);
});

//keypress code
var keysElement = document.getElementById('keyPressed');

window.addEventListener("keyup", function() {
   buttonPressed = false;
   keysElement.innerHTML = "Keys not Pressed";
   clearTimeout(timer);
   timer = setTimeout("keysPressed", 300);
});

window.addEventListener("keydown", function() {
   buttonPressed = true;
   keysElement.innerHTML = "Keys Pressed";
   clearTimeout(timer);
   timer = setTimeout("keyPressed", 300);

});

function checkTime(i) {
   if (i < 10) {
      i = "0" + i
   }; // add zero in front of numbers < 10
   return i;
}

Here is the HTML code:

<body onload="idleTime()">


    <div id="stopped"><br>Mouse stopped</br></div>
    <div id="keyPressed"> Keys not Pressed</div>

    <strong>
      <div id="header"><br>Time Idle:</br>
      </div>
    <div id="idle"></div>


    </strong>
  </body>



via Chebli Mohamed

Angular-Slick and dynamic data not initializing correctly

I'm using the angular-slick directive because I have found this to work best for me in most instances. However, I'm still having a problem with getting the slides to initialize properly with dynamic data.

I have a dropdown that updates the relatedResorts json object in a factory. My controller watches for this update and updates scope.relatedResorts accordingly. That all works fine.

Before the slider updates, the slides/content+images are there and it looks like its working. The slick-initialized class has been applied and the excess slides are hidden. But they won't drag or auto advance and the arrows don't even show up.

I then make the images clickable so you can update the json object by clicking on one of the cards as well. The slider actually works better after an image is clicked and the object is refreshed, oddly enough, but the arrows still won't work. You can even drag the slider and see the other slides.

I have tried slick and unslick (which works only after the dom is loaded even with a $timeout applied and seems like a bit of a hack), creating my own directive, and $timeout. I've racked my brains trying to figure this one out.

help please...

HTML:

<slick class="row slider" arrows="true" responsive="breakpoints" slides-to-show=3 slides-to-scroll=1 dots="false" infinite="true" speed="300" touch-move="false" ng-if="relatedResorts.length" init-onload=true data="relatedResorts">
    <div class="card col-md-4 col-sm-6 col-xs-12" ng-repeat="option in relatedResorts" ng-click="resetResort(option.id)">
        <div class="img-container"> 
                <div class="banner">
                <p>{{option.resort_name}}</p>
            </div>
            <img ng-src="assets/images/resorts/{{option.id}}/{{option.resort_img}}" alt="Luxury Resort: {{option.resort_name}}"/>
        </div>
    </div>
</slick>

CONTROLLER:

resortModule.controller('relatedResortsController', ['$scope', 'locaService', '$timeout', function($scope, locaService, $timeout) {
    $scope.relatedResorts;
    $scope.resort;
    $scope.getRelated = function (resort) {
        //Resorts in location/destination on location change
        locaService.fetchRelatedResorts(resort).then(function(result) {
            $scope.relatedResorts= result;
        });
    }
    $scope.resetResort= function(resort){
        //reset resort for app when related resort image is clicked on. 
        $scope.resort= resort;
        locaService.updateResort(resort);
        /*$(".slider").slick('unslick');
        $(".slider").slick();*/
    }

    //watches factory for updates to objects
     $scope.$on('resortUpdated', function() {
        $scope.resort = locaService.resort;
        $scope.getRelated($scope.resort);
    });
}]);



via Chebli Mohamed

How to dynamically append templates to a page in Angular

So the situation is as follows:

I have an input bar where a user can search up a business name or add a person's name (and button to select either choice). Upon hitting enter I want to append a unique instance of a template (with the information entered by the user added). I have 2 templates I've created depending of if the user is searching for a business or a person.

One approach I've thought about is creating an object with the data and adding it with ng-repeat, however I can't seem to get the data loaded, and even then don't know how I can store reference to a template in my collection.

The other idea I've come across is adding a custom directive. But even then I've yet to see an example where someone keeps appending a new instance of a template with different data.

Here is the code so far:

payments.js:

angular.module('payment-App.payments',['ngAutocomplete'])

  .controller('paymentController', function($scope, $templateRequest/*, $cookieStore*/) {

    $scope.businessID;
    $scope.address;
    $scope.isBusiness = false;
    $scope.payees = [];

    $scope.newPayee = function () {
      this.businessID = $scope.businessID;
      this.address = $scope.address;
    }

    $scope.submit = function () {
      var text = document.getElementById("businessID").value.split(",");
      $scope.businessID = text[0];
      $scope.address = text.slice(1).join("");
      $scope.newPayee();
    }

    $scope.addPayee = function () {
      $scope.submit();
      $scope.payees.push(new $scope.newPayee());
      console.log($scope.payees);
    }

    $scope.selectBusiness = function () {
      //turns on autocomplete;
      $scope.isBusiness = true;
    }

    $scope.selectPerson = function () {
      //turns off autocomplete
      $scope.isBusiness = false;
    }

    $scope.fillAddress = function () {
      // body...
    }

})

  .directive("topbar", function(){
  return {
    restrict: "A",
    templateUrl: 'templates/businessTemplate.html',
    replace: true,
    transclude: false,
    scope: {
      businessID: '=topbar'
    }
  }
})

payments.html

<h1>Payments</h1>

<section ng-controller="paymentController">


<div>

  <div class="ui center aligned grid">

    <div class="ui buttons">
      <button class="ui button" ng-click="selectBusiness()">Business</button>
      <button class="ui button arrow" ng-click="selectPerson()">Person</button>
    </div>

    <div class="ui input" ng-keypress="submit()">
      <input id="businessID" type="text" ng-autocomplete ng-model="autocomplete">
    </div>


    <div class="submit">
      <button class="ui button" id="submit" ng-click="addPayee()">
        <i class="arrow right icon"></i>
      </button>
    </div>

  </div>

  <div class="search"></div>


  <div class="payments" ng-controller="paymentController">
    <li ng-repeat="newPayee in payees">{{payees}}</li>
  </div>

  <!-- <topbar></topbar> -->

</div>

(example template) businessTemplate.html:

 <div class="Business">
   <div class="BusinessName" id="name">{{businessID}}</div>
   <div class="Address" id="address">{{address}}</div>
   <button class="ui icon button" id="hoverbox">
     <i class="dollar icon"></i>
   </button>
 </div>



via Chebli Mohamed

Is there a way to remove the extra wrapping div around a CollectionView in Marionette js 2.x?

I see ways to remove from ItemViews and Layouts but not the CollectionView. Override attachHTML? Using the CollectionView's tagName property to target an element won't work for me because I need the collection items to render directly into an already existing DOM element, not a new one generated by the CollectionView.



via Chebli Mohamed

FB change share location

How can I make "In a private message" value by default? I think this value affects "action_type", found only this example:

  FB.ui({
    method: 'share_open_graph',
    action_type: 'og.likes',
    action_properties: JSON.stringify({
      object:'http://ift.tt/1nt9Vwm',
    })
  })

share dialog

I know about FB.ui({method: 'send'}), but I need share dialog with "In a private message" by default.



via Chebli Mohamed

Get First line in Summernote

i can't get the first line of text using Summernote WYSIWYG Editor, i try using indexof of last
but not work.

how could you do this?

Thx.



via Chebli Mohamed

three;js: Error trying to access class after adding information to it

Playing around with classes / prototypes. Basically I'm trying to get a 3d cube to face the direction the mouse is in. I think it's almost there, but right now it's not rendering the cube, which it was doing fine before I added this code:

cube.look(xTarget, yTarget);

which is giving this error:

 Uncaught TypeError: Cannot read property 'look' of undefined`

What am I doing wrong here? Why is it unable to access the var cube? (which is what I think the problem is).

Here's a plunkr

Here's the relevant js:

Cube.prototype.updateBody = function(speed){
    this.box.rotation.y += (this.tBoxRotY - this.box.rotation.y) / speed;
    this.box.rotation.x += (this.tBoxRotX - this.box.rotation.x) / speed;
    this.box.position.x += (this.tBoxPosX-this.box.position.x) / speed; 
    this.box.position.y += (this.tBoxPosY-this.box.position.y) / speed; 
    this.box.position.z += (this.tBoxPosZ-this.box.position.z) / speed; 
}

Cube.prototype.look = function(xTarget, yTarget){
    this.tBoxRotY = rule3(xTarget, -200, 200, -Math.PI/4, Math.PI/4);
    this.tBoxRotX = rule3(yTarget, -200,200, -Math.PI/4, Math.PI/4);
    this.tBoxPosX = rule3(xTarget, -200, 200, 70,-70);
    this.tBoxPosY = rule3(yTarget, -140, 260, 20, 100);
    this.tBoxPosZ = 0;
}

function loop() {
      render();
    var xTarget = (mousePos.x-windowHalfX);
    var yTarget= (mousePos.y-windowHalfY);
    console.log('Mouse X position: ' + xTarget +', Y Target = '+yTarget );
    cube.look(xTarget, yTarget);
    requestAnimationFrame(loop);
}



via Chebli Mohamed

Node.js bluebird.map unexpected result

I've been working with node.js and I need to check an array with jsons and update some of the items and in the end return the updated array. What I'm doing is something like the following: (The main app uses express and sequelize)

exports.getDetails = function (req, res) {
  var accountsArray = [];

  bluebird.map(req.accounts, function(account, callback){
     if (account.type == 'A'){
         if (account.param == req.body.paramSearch){
            account.updateAttributes({
                   param: req.body.paramSearch
            }).then(function(updatedAccount){
                console.log('A type entry');
                accountsArray.push(updatedAccount);
            });
         }
         else{
            console.log('A type entry');
            accountsArray.push(account);
         }
     }
     if (account.type == 'B'){
         if (account.param == req.body.paramSearch){
            account.updateAttributes({
                   param: req.body.paramSearch
            }).then(function(updatedAccount){
                console.log('B type entry');
                accountsArray.push(updatedAccount);
            });
         }
         else{
            console.log('B type entry');
            accountsArray.push(account);
         }
     }
  }).then(function(){
     console.log('Bluebird.map done');
     res.status(200).json({
        data: {
           accounts: accountsArray
        }
     });
  });

What I intended it to do was to first add all the accounts (victims of update or not) to the accountsArray and only then return the json with the accountsArray.

Instead what I get is an empty accountsArry. I used the console.logs in the code to follow how things where being processed. What I always get is something like

Bluebird.map done
A/B type entry
...
A/B type entry

The expected was

A/B type entry
...
A/B type entry
Bluebird.map done

I'm new to node.js and this asynchronous processing still gets me confused. Is there anyway to ensure that I've finished the subfunctions inside the map part and only then move on to the response? If possible, using Bluebird.

Any help is dearly appreciated.



via Chebli Mohamed

JavaScript subtring method

I need to get a substring from a json. Presently from the JSON, i have extracted the string i need.

I need to check if the variable contains either the word 'refunded' or 'accepted', then this String within square brackets (where the string was found) is to be extracted. The words 'refunded' or 'accepted' if they appear, then they will be within [] along with the rest of the string. The entire string may contain more [] but i need to extract the string immediate within [] containing either or both the string. e.g. the variable is The String is in format as the variable description.

var description="TopSport  $300.00 @ $9.00, [DONALD R2] : 7 [Only $125 was accepted. $175 refunded.]";

Since it contains both accepted/refunded (even either of the word appear the extraction is required), then this is to be taken out of the entire string.

[Only $125 was accepted. $175 refunded.]



via Chebli Mohamed

I want to combine first function to the second one, so I can call it only once

I want to combine first function to the second one, so I can call it only once. Basically i have 2 html5 audio files that im playing. Everything works fine.But if i play my first audio and during that time if i click the second audio the pause button on first audio doesn't change to default(off)

//First function 

function toggleState(item) {
  if (item.className == "play") {
    item.className = "pause";
  } else {
    item.className = "play";
  }
}

//Second function
// Play stop Music
function EvalSound(soundobj) {
  var thissound = document.getElementById(soundobj);
  if (thissound.paused) {
    thissound.play();
  } else {
    thissound.pause();
  }
}



via Chebli Mohamed

Event listener can't read correct return from another function

I have some code where I have set up an event listener. The event listener looks something like this:

api.setListener(function(message) {
    myFunction(message);
});

This is obviously not the actual code, but it's the same idea.

This event listener will be called/run every single time the api receives a message from the server. Upon receiving a message, the api will call myFunction and pass in message to it.

The myFunction looks like this:

function myFunction(message) {
    var otherStuff = getOtherStuff(message.name);

    if(otherStuff.isGood) {
        ...
    }
}

The checkGoodness function is a function that, based on the message name passed in to it, will search through an object and will return the key of that object with the same .name property.

The getOtherStuff function looks like this:

function getOtherStuff(name) {
    for(var thing in obj) {
        if(obj.hasOwnProperty(thing)) {
            if(obj[thing].name === name) {
                return obj[thing];
            }
        }
    }
    return null;
}

Now here is where the problem comes in: even though the name may exist in a property of obj, this function will always return null.

But this is very confusing. I have set up many console.logs to log...

  • obj.

  • obj[thing].

  • name, to make sure it was passed in correctly.

  • "good" if the conditional passed and return obj[thing] is about to run.

  • "bad" if it did not pass and return null is about to run.

And everything seems as expected: obj and it's properties are correct, name is passed in correctly, "good" is printed, "bad" is not: everything seems all perfect.

However, when I insert a console.log into myFunction to check the return of getOtherStuff, I get null.

What is causing this? Why? Is it something to do with the event like I predict?



via Chebli Mohamed

Fadeout page after animation finishes

I want an animation (function handleScreen(mql)) to run and after it is completed, for the page (#splash,#name) to fade out. I tried adding a .done function but that doesn't seem to work. Any help would be very much appreciated.

$(document).ready(function() {

        $("#splash,#name").show()

        var mql = window.matchMedia("(max-width: 480px)");

        function smallBlock() {
            //STUFF
        };

        function largeBlock() {
           //STUFF
        };

        function handleScreen(mql) {
            if (mql.matches) {
                smallBlock();
            } else {
                largeBlock();
            }

            mql.addListener(handleScreen);
            handleScreen(mql);
        };

        $.when(handleScreen(mql).done(function() {
                    setTimeout(function() {
                        $("#name,#splash").fadeOut("slow")
                    }, 1000)
                });



via Chebli Mohamed

How do i add content in an div with javascript?

How do i change the content of an div on an website that has an id with javascript?

<div class="chat-area" id="chat-area">[Changeable]</div>

I want to know how i add content where it says "[Changeable]" with javascript so i can run the command through the console. I'd like if you keep your explainage simple, because im still very new to html/css/javascript ;)



via Chebli Mohamed

Working with $_POST from ajax in symfony controller

I'm beginner to symfony. I have a twig template with 2 buttons that calls an external .js that executes an ajax call.

Button 1 calls function 'delete', and this is the js code:

    var path = $("#abc").attr("data-path");
 /*grabs it from some div in the twig template.. <div id="abc" data-path="{{path('delete')}}"></div>*/

    function delete(n){
        $.ajax({
          type: "POST",     
          url: path,
          data: {id : n},
          "success":function(data){
          alert('ok');
          }
          });
    }

Button 2 calls function 'edit' which is the same code except that the 'url' goes to another 'action', and the 'data' is not a json, (it is data: formData)

Routing.yml for function delete is:

    delete:
        pattern:  /delete
        defaults: {_controller: TPMainBundle:Default:delete }  

And this is the controller action:

public function deleteAction()
    {
 $id = $_POST['id']; 
 /*other code to work with doctrine making queries to delete from database*/ 
}

(The js code is from a webpage done without symfony and it works fine)

I was told the right way to retrieve the POST in the action, reglardless it was whether a json or formData, was using the same that I used in PHP:

 $id = $_POST['id']; 

Here, I have 2 problems.

First, I don't know if this is correct because it doesn't work.

Second, I don't know how can I know if i'm retrieving the POST OK !!

When I did this without symfony, I checked if I was getting the POST with the command 'fwrite', because the ajax went to a PHP file instead of an Action, and then with the command fwrite I created a .txt file with the output of an echo to see if the $_POST was recovered or not.

But here in symfony I don't know how to check it, so I'm driving myself crazy.. trying to implement the solutions I read without being sure if they work..

and with the extra problem that since I'm newbie for me it's a bit confusing trying to install some external bundles for debug. Please help



via Chebli Mohamed

Infinite scroll within Ajax

So, I have Ajax enabled on my Wordpress site as the following:

id within any anchor within the chosen div will be saved and used to find an appropriate php file then loaded at an appropriate content div.

PHP

<!--Menu part -->
 <div class="royal_front_menu">
      <a href="#rcp_front_front_id" class="mdl-tabs__tab is-active" id="front_id">All</a>       
      <a href="#rcp_front_electronic_id" class="mdl-tabs__tab" id="electronic_id">Electronics</a>         
</div>

<!--Content Part-->
<div class="active" id="rcp_front_front_id">  
     <div class="spinner"></div>
</div>
<div class="not_active" style="display:none;" id="rcp_front_electronic_id"> 
     <div class="spinner"></div> 
</div>      


<script>
//Ajax loading
jQuery(document).ready(function() {
    jQuery('.royal_front_menu a').click(function(e) {
        e.preventDefault();

        var tab_id = jQuery(this).attr('id'); 

        jQuery.ajax({
            type: "GET",
            url: "<?php echo admin_url('admin-ajax.php'); ?>", 
            dataType: 'html',
            data: ({ action: 'royal_front_tab', id: tab_id}),
            success: function(data){
                  jQuery('#rcp_front_' + tab_id).html(data);


        },
        error: function(data)  
        {  
        alert("Error!");
        return false;
        }  

        }); 

 }); 
 });
</script>

FUNCTION.PHP

//Ajax call for front page for Mobile
function royal_front_tab_rhm_callback() {  
     $template_part_path = 'page-parts/rhm/front/01_front_menu_' .  $_GET['id'];
get_template_part($template_part_path);
exit;
}
 add_action('wp_ajax_royal_front_tab_rhm', 'royal_front_tab_rhm_callback');
 add_action('wp_ajax_nopriv_royal_front_tab_rhm', 'royal_front_tab_rhm_callback');

01_front_menu_front_id.php

<div class="content">
    <?php echo do_shortcode('[Post_Shortcode]'); ?> 
</div>

So far so good...

So, with the following setup, everything is working fine. All the contents are called only when clicked etc. GREAT!

However, I am trying to add one more feature: Infinite scroll

What I have done so far:

I followed the following instruction: http://ift.tt/L0bQWp

So, I tried this on a separate dummy site to see how it works before messing things up.

SET UP

Add the following to the function.php:

// To add infinitescroll js
function custom_theme_js(){
    wp_register_script( 'infinite_scroll',  get_template_directory_uri() . '/custom_js/jquery.infinitescroll.min.js', array('jquery'),null,false );
    wp_enqueue_script('infinite_scroll');

}
add_action('wp_enqueue_scripts', 'custom_theme_js');

//To add selectors
function custom_infinite_scroll_js() {
    { ?>
    <script>
    jQuery('.royal_card.site-row-fluid.site-grid-list').infinitescroll({
        navSelector  : jQuery('.site-pagination'),
        nextSelector : jQuery('.site-pagination > a.next'),
        itemSelector :  '.royal_card.site-row-fluid.site-grid-list > .royal_card_outer.royal_card_content_grid',
        contentSelector: jQuery('.royal_card.site-row-fluid.site-grid-list'),
    msgText: "Yay"  
    },function(newElements){
        jQuery('.site-separator').remove();
        jQuery('.royal_card.site-row-fluid.site-grid-list > .royal_card_outer.royal_card_content_grid').after('');
     });
    </script>
    <?php
     }
 }
add_action( 'wp_footer', 'custom_infinite_scroll_js',100 );

When I tried this on a dummy site (without Ajax), it works fine. I can get the next page content as infinite scroll.

The "Normal" URL from the dummy site is this:

 <a class="page-numbers" href="http://ift.tt/1zVzOFL">2</a>

Problem

So, with the Ajax page, I found something peculiar. The page URL became somewhat odd:

 <a class="page-numbers" href="http://ift.tt/1ILDSQ4">2</a>

Because it is not a normal URL, it leads to a "404" page as it does not exist.

Here is my guess

I thought that jQuery('.royal_front_menu a').click(function(e) { which any anchor within royal_front_menu div will be affected. But the content is loaded outside of the div.

Okay, I am confused to why it is happening.

Any suggestions?



via Chebli Mohamed

Remove global flag from RegExp

Given a user (developer) provided regular expression, I need to remove the global flag if it exists. On firefox 38 and above you can just set it1 :

the_regex.global = false;

However that is not supported elsewhere. So, I have created this pair of functions:

function deGlobal(regex){
    if(!regex instanceof RegExp)return regex;
    if(!regex.global)return regex;
    var parts = regExpParts(regex);
    console.log(parts);
    if(parts){
        return new RegExp(parts.pattern,parts.flags.replace("g",""));
    } else {
        return false;
    }
}
function regExpParts(regex){
    if(!regex instanceof RegExp)return false;
    var regex_string = regex.toString();
    var flags = regex_string.substring(regex_string.lastIndexOf('/')+1);
    var pattern = regex_string.substring(1,regex_string.lastIndexOf('/'));
    return {flags:flags,pattern:pattern};
}

fiddle: http://ift.tt/1Par3As

Which for all of my test cases is doing great, but it seems like a very error prone method. Is there a case where these functions wouldn't work? Is there a better cross browser method of doing this?

1 http://ift.tt/1TxneMc



via Chebli Mohamed

adding mutiple filters using jquery

Hi guys so with some help and messing around i got a table working in html with filters but i still have problem :

1.I'm trying to have multiple filters working at once, i trying to have it shows the quest type aswell as if has or has not been completed

2.I am unable to get the completed quest filter to work I have added a checkbox filter to add a class to the row based on wether the box has been ticked or not it adds class: completed when checked and class: notCompleted when unchecked but now it wont filter them

my fiddle if you need it here

heres my code for jquery :

    // Filter Row Script Type of Quest
// ........................................
$('.filterMenu a').on('click', function (e) {
    e.preventDefault();
    var c = $(this).data('qtype');

    //get all trs from tbody
    var trs = $("#questTable").find("tbody tr");
    trs.hide();

    //Filter all trs from tbody
    trs.filter(function (i, v) {
        if ($(this).data("qtype") == c) {
            return true;
        }
        if (c == "all") {
            return true;
        }
        return false;
    })
    //just show the row if it fits the criteria
    .show();

});

// Filter Row Script Quest Completed or Not
// ........................................
$('.filterMenuCompleted a').on('click', function (e) {
    e.preventDefault();
    var c = $(this).attr('class');

    //get all trs from tbody
    var trs = $("#questTable").find("tbody tr");
    trs.hide();

    //Filter all trs from tbody
    trs.filter(function (i, v) {
        if ($(this).attr("class") == c) {
            return true;
        }
        if (c == "all") {
            return true;
        }
        return false;
    })
    //just show the row if it fits the criteria
    .show();

});

And here my html :

<body>
    <div id="content">
        <div class="filterMenuCompleted">
                <ul>
                    <li><a href="#" class="all">All</a></li>
                    <li><a href="#" class="completed">Completed</a></li>
                    <li><a href="#" class="notCompleted">Not Completed</a></li>
                </ul>
            </div>
        <div class="filterMenu">
            <ul>
                <li><a href="#" data-qtype="all">All</a></li>
                <li><a href="#" data-qtype="mcq">Main Scenario</a></li>
                <li><a href="#" data-qtype="sq">Side Quest</a></li>
            </ul>
        </div>
        <table id="questTable" style="max-width: 800px;" class="all">
            <thead>
                <tr>
                    <th class="table-header">#</th>
                    <th class="table-header">Type</th>
                    <th class="table-header">Icon</th>
                    <th class="table-header">LvL</th>
                    <th class="table-header">Name</th>
                    <th class="table-header">Issuing NPC</th>
                    <th class="table-header">Location</th>
                    <th class="table-header">Done It?</th>
                </tr>
            </thead>
            <tbody>
                <tr id="line1" class="table-row" data-qtype="mcq">
                    <td class="shortTd">MC-1</td>
                    <td class="shortTd">Main Scenario</td>
                    <td class="shortTd">
                        <img src="./images/Quests/Main_Scenario/mc.png" alt="" />
                    </td>
                    <td class="shortTd">1</td>
                    <td> <a href="#"> mcq 1</a>

                    </td>
                    <td>Name 1</td>
                    <td>Area 1</td>
                    <td class="shortTd">
                        <input class="completion" type="checkbox" id="checkbox1">
                    </td>
                </tr>
                <tr id="line2" class="table-row" data-qtype="mcq">
                    <td class="shortTd">Mc-2</td>
                    <td class="shortTd">Main Scenario</td>
                    <td class="shortTd">
                        <img src="./images/Quests/Main_Scenario/mc.png" alt="" />
                    </td>
                    <td class="shortTd">1</td>
                    <td> <a href="#">mcq 2</a>

                    </td>
                    <td>Name 2</td>
                    <td>Area 2</td>
                    <td class="shortTd">
                        <input class="completion" type="checkbox" id="checkbox2">
                    </td>
                </tr>
                <tr id="line2" class="table-row" data-qtype="sq">
                    <td class="shortTd">Sq-1</td>
                    <td class="shortTd">Side Quest</td>
                    <td class="shortTd">
                        <img src="./images/Quests/Main_Scenario/mc.png" alt="" />
                    </td>
                    <td class="shortTd">1</td>
                    <td> <a href="#">Side quest</a>

                    </td>
                    <td>Name 3</td>
                    <td>Area 3</td>
                    <td class="shortTd">
                        <input class="completion" type="checkbox" id="checkbox2">
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    <div id="footer">Brought to you by Vesper Tia @ Moogle
        <br/>&copy; 2010 - 2015 SQUARE ENIX CO., LTD. All Rights Reserved.</div>
</body>

And of course my css :

/*Global Resets*/

/*....................................*/
 * {
    margin:0;
    padding:0
}
html {
    font-family:Arial, sans-serif;
    font-size:1em
}
h1, h2, h3 {
    margin:0 auto 1em;
    text-align:center
}
h1 {
    margin-top:1em;
    margin-bottom:0
}
h2 {
    color:#e8d19e
}
h3 {
    color:#5a9dd1
}
h4 {
    margin-bottom:.5em;
    padding-bottom:20px;
    text-align:center
}
a {
    color:#CC9900;
    text-decoration:none;
    font-weight:700
}
p {
    margin-bottom:1em;
    text-align:justify;
    line-height:1.3em
}
img {
    max-width:100%
}
table {
    margin:1em auto 3em;
    border-collapse:collapse
}
table th {
    padding:.5em 1em;
    height:2em;
    font-weight:700;
    color:#9ba3b6;
    text-shadow:0 0 5px #000;
    border-bottom:solid 1px #222;
}
table td {
    padding:.5em 1em;
    height:2em;
    background-color:#282828;
    border-bottom:solid 1px #666;
    line-height:1.4em;
    text-align:left
}
#content {
    padding:1em;
    color:#DDD
}

.filterMenuCompleted ul{height: 20px;float: left; margin-right: 50px;}
.filterMenuCompleted ul li{
    display: block;
    float: left;
    margin-right: 5px;
}

.filterMenu ul{height: 20px;float: left; margin-right: 50px;}
.filterMenu ul li{
    display: block;
    float: left;
    clear: right;
    margin-right: 5px;
}
/*Responsive Settings*/

/*...............................................*/
 @media all and (max-width: 500px) {
    table {
        font-size:.8em
    }
    .npcFullCardName, .npcIcon img {
        display:none
    }
    .cardLocation {
        padding:15px;
        width:300px;
        background-size:300px;
        left:-85px;
        font-size:.8em
    }
}
@media all and (min-width: 501px) {
    .npcFullCardName {
        display:inline;
        color:#9c9;
        cursor:help
    }
}
@media all and (max-width: 1023px) {
    html {
        background:url(../images/background_low.jpg) no-repeat top center fixed #000
    }
    table {
        min-width:100%;
        width:100%
    }
}
@media all and (min-width: 1024px) {
    html {
        background:url(../images/background.jpg) no-repeat center center fixed #000;
        -webkit-background-size:cover;
        -moz-background-size:cover;
        -o-background-size:cover;
        background-size:cover
    }
    #content {
        margin:0 auto;
        max-width:1000px
    }
}
}
/*Row Highlight*/

/*................................................................*/
 .current-row td {
    background-color:#1b1b1b;
    color:#FFF
}
.completed td {
    opacity: 0.3
}



via Chebli Mohamed

Jascript - Comparing 2 Arrays of Object in the fastest and cleaner way

Assuming we have 2 arrays, A (source) and B (being saved).

var A = [ 
      { id: 1, value: 'Product Name 1' },
      { id: 2, value: 'Product Name 2' },
      { id: 3, value: 'Product Name 3' },
      { id: 4, value: 'Product Name 4' },
      { id: 5, value: 'Product Name 5' } 
]


var B = [ 
      { id: 1, value: 'Product Name 1' },
      { id: 2, value: 'Changed Name' },
      { value: 'New Product' }
]

Basically what i want to do is to compare both arrays, and check on array B, items are not present from array A which got deleted, the ones that had the 'value' property changed which got edited, and which ones are new which got added (basically without an id).

A logic goes like that (assuming that each A and B are one element from each array)

if A.id == B.id and A.value !== B.value then Edit

B.id doesnt exist then New

B.id is not on A then Deleted

I need to have a array of all the elements that got Added, Edited and Deleted

Expected Array would be

added = [ 
      { value: 'New Product'} 
]

edited = [ 
      { id: 2, value: 'Changed Name' }
]

deleted = [
      { id: 3, value: 'Product Name 3' },
      { id: 4, value: 'Product Name 4' },
      { id: 5, value: 'Product Name 5' } 
]



via Chebli Mohamed

How does web client request visualization session for ParaViewWeb launcher?

I have a Pyramid web application on which I would like to embed an iFrame displaying an instance of ParaViewWeb's visualizer so users can display VTU files remotely.

I have successfully done so while running the application on my own workstation by calling a subprocess from Python that executes ParaViewWeb's Quick Start method and returns the URL to JavaScript for iFrame generation.

http://ift.tt/1h7Ttk4

However, in order to accommodate multiple users, ParaViewWeb's documentation indicates that

the server must provide a single entry point to establish a connection, as well as a mechanism to start a new visualization session on demand

for which it suggests using Apache as the front-end application and a python launcher to start the process for each session.

Conveniently, I have a "freshly installed Ubuntu Desktop 14.04 LTS" so I used the following guide to configure both the launcher and Apache:

http://ift.tt/1J3mNy5

Ok so I'm pretty sure I am missing something major here, but once the launcher is started with /data/pvw/bin/start.sh... how do I then submit the request with information regarding what app to use (visualizer) and what data directory to load???



via Chebli Mohamed

Select element in angular not updating modelValue on second selection

I've got a select element bound to a model in an angular view. When filling out the form with the keyboard, I noticed that if you down arrow to the second option the value, the model still represents the first value. This only happens when using the keyboard to fill out the form.

Set up is pretty simple, using angular 1.4.3:

var app = angular.module('app', []);

app.controller('myController', function() {
  var vm = this;

  vm.options = [{
    Id: 1,
    Value: 'A'
  }, {
    Id: 2,
    Value: 'B'
  }, {
    Id: 3,
    Value: 'C'
  }]
});
<script src="http://ift.tt/1g2WAJw"></script>

<body ng-app="app">
  <div ng-controller="myController as ctrl">
    <p>
      Model is not updated on second down button push. Repro:
      <ol>
        <li>Tab to select element</li>
        <li>Hit down and notice the optionId updated to 1</li>
        <li>Hit down again and notice that the displayed value changes to B, but optionId stays as 1</li>
        <li>Hit down again and notice that the displayed value changes to C, and optionId changes to 3</li>
        <li>Hit up and notice that displayed value changes to B, and optionId changes to 2</li>
      </ol>
      Why doesn't the optionId = 2 on the initial selection of B
    </p>
    <select id="mySelect" ng-options="item.Id as item.Value for item in ctrl.options" ng-model="ctrl.optionId" style="width:200px">
    </select>
    <div><strong>optionId: {{ctrl.optionId}}</strong>
    </div>
  </div>
</body>

Why doesn't the model update on the second down arrow press?

Update: Here's a plunker that exhibits the behavior, http://ift.tt/1J3mNy2



via Chebli Mohamed

HTML File input with possibility to input several files one after another

I'm looking for a possibility to input several files in a row in an HTML form. It strikes me that there seems to be no easy solution for this (or at least I haven't been able to find it despite several hours of searching). If I use the multiple attribute in an <input type="file" name="myFiles[]" multiple />, I can choose several files at a time holding Ctrl, but if I choose one file at first, then click the input field again and choose another one, the second file seems to overwrite the first one. So I thought I might try to use javascript to add more fields since I have seen something similar somewhere. I tried thie following:
JavaScript:

function addInputFileEle() {
    var field = document.getElementById("filesField");
    var row = '<input type="file" name="myFiles[]" onchange="addInputFileEle();" />';
    field.innerHTML += row; // add one more <input type="file" .../> element
}

HTML:

<form method="post" action="#">
     <fieldset id="filesField"> <!--for adding more file-input rows-->
         <input type="file" multiple name="myFiles[]" class="multi" <!--onchange="addInputFileEle();"--> />
     </fieldset>
     <input type="submit"/>
 </form>

The document indeed does create additional file-input elements whenever I click on one of them and select a file, BUT: The file does not get uploaded! I mean, after I select the file, the file name does not get displayed, instead, it still says "Choose a file" (or "Select a file", don't know what exactly in English). So apparently my onchange() function overwrites the normal reaction, which is, the file is 'loaded' into the input element? Even though this does not seem logical to me. Can anyone help? Maybe there is a simpler solution than mine, which would of course be very welcome. Thanks in advance!



via Chebli Mohamed

img insert into HTML from javascript

So I am trying to insert images into <marquee> from a js file. This is what my js file looks like?

      function buildList(){
            var data= ['logo1.png', 'logo2.png', 'logo3.png'];

            //var data2 = [{2:"hello"},{3:"world"},{6:"PSI"},{4:"ali"},{7:"buck"},{1:"hello"},{8:"albert"},{5:"wow"}];
            var marquee = document.getElementsByTagName('marquee');


            for(var i in data){

                    var img = new Image();
                     img.onload = function() {

                    //var newListItem = ' ' + data[i] +  ' there should be an img coming in from an array here';


                                   return img;
                };
                    img.src = data[i];
                    marquee[0].innerHTML  +=  img ;
            //http:http://ift.tt/1cWxZTP"alt="Milford Sound in New Zealand' "Width=80 Height=80" ' + img;
            }   







        }

However when I look at the developer console in chrome, I get no error messeges by inside the marquee it is giving me [object HTML ImageElement]... What am i doing wrong?



via Chebli Mohamed

How to draw Canvas in WebView?

I'm making an app where people will be able to place circles in WebView. So, my algorithm is:

  1. Detect long click
  2. Get finger coordinates on WebView
  3. Draw circle in Canvas

I tried different methods, used different approaches - making personal DrawWebView class, detecting long press in MainActivity and then drawing circle in DrawView and list goes on, yet nothing works.

For starters I decided to set up custom WebView and draw circle in fixed position(330, 618). I manage to draw it, but when I start to zoom in, circle moves.

public class DrawWebView extends WebView{

    PointF zoomPos;
    static DrawWebView wv1;
    public DrawWebView (Context context, AttributeSet attrs)
    {
        super (context, attrs);
        wv1 = (DrawWebView) findViewById(R.id.webView1);
        wv1.loadUrl("file://" + Environment.getExternalStorageDirectory() + "/Pictures/boxes.jpg");
        wv1.getSettings().setBuiltInZoomControls(true);
        wv1.getSettings().setDisplayZoomControls(false);
        wv1.getSettings().setSupportZoom(true);
        wv1.getSettings().setUseWideViewPort(true);
        wv1.getSettings().setLoadWithOverviewMode(true); 
        wv1.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
    }

    public boolean onTouch(View v, MotionEvent event) {

        int action = event.getAction(); 


        switch (action) { 
        case MotionEvent.ACTION_DOWN:
            break;
        case MotionEvent.ACTION_MOVE:
            this.invalidate();
            break;

        case MotionEvent.ACTION_UP: 
            this.invalidate();
            break;
        case MotionEvent.ACTION_CANCEL:

            break; 

        default: 
            break; 
        }
        return true;
    }


    @Override
    protected void onDraw(Canvas canvas) 
    {
        super.onDraw (canvas);

        zoomPos = MainActivity.zoomPos;
        Paint p = new Paint();
        p.setColor (Color.RED);
        canvas.drawCircle(330, 618, 10, p);
        //canvas.drawCircle(100, 100, 100, p);


    }
}

If you know how to do this or know a good tutorial - it would be much appreciated.



via Chebli Mohamed

Angular unit testing $interval for a "clock" directive

I have an Angular directive "clock" and I'm trying to write a unit test to see if the clock actually $interval advances to a future time (ie: 2 minutes by looking at element.text()). I have a passing test of the current time, now I want to test if it will show a future time via $interval.flush. It appears to me $interval.flush isn't really advancing the clock.

Sure, there may be other strategies to test if $interval fires, but it would be helpful to the community (and my sanity) to answer why $interval.flush doesn't seem to be doing what I think it should be doing.

I'm following guidelines from these posts:

A related post suggested using Jasmine mocks, which I don't think is necessary anymore.

HTML

  <mydatething format="EEEE, MMMM d" interval="1000" timezone="notused"></mydatething>

DIRECTIVE

myApp.directive('mydatething', ['$interval', 'dateFilter', function ($interval, dateFilter) {
  return {
    restrict: "AE",
    scope: {
      format: '@',
      interval: '@'
    },
    template: '', // the template is the Date() output
    link: function (scope, element, attrs) {

      // scope expects format, interval and timezone
      var clockid;
      var clockinterval = scope.interval;
      var dateformat = scope.format;
      var clocktimezone = scope.timezone;

      // DOM update function
      function updateClock() {
        element.text(dateFilter(new Date(), dateformat));
      }

      // Instantiate clock
      updateClock();
      clockid = $interval(updateClock(), clockinterval);

      // For cancelling 
      scope.$on('$destroy', function () {
        $interval.cancel(clockid);
      });

      // Separate listener for locale change, manually refresh clock format
      scope.$on('$localeChangeSuccess', function () {
        updateClock();
      })
    }
  };
}]);

UNIT TEST

describe("tsdate directive", function(){
  var elem, scope, $interval, dateFilter;
    beforeEach(module('tsApp'));
    beforeEach(inject(function(_$rootScope_, _$interval_, _$compile_, _dateFilter_){
    $compile = _$compile_;
    dateFilter = _dateFilter_;
    $interval = _$interval_;
    $rootScope = _$rootScope_;
    scope = $rootScope.$new();

    elem = angular.element('<mydatething format="h:mm a" interval="15000"></mydatething>');
    elem = $compile(elem)(scope);
    scope.$digest();

    }));
    describe('on clock start', function() {
    it('to show the current date', function() {
      var currentdate = dateFilter(new Date(), elem.isolateScope().format);
      expect(elem.text()).toBe(currentdate);
      // this passes
    });
    it('that it updates the clock', function() {
      var futurems = 120000; // 2 minutes
      var futuredate = dateFilter(new Date().getTime() + futurems, elem.isolateScope().format)
      $interval.flush(futurems);
      expect(elem.text()).toBe(futuredate);
     // this fails
    });
    });

});

TERMINAL

PhantomJS 1.9.8 (Mac OS X) mydatething directive on clock start that it updates the clock FAILED
    Expected '3:55' to be '3:57'.

Console.log reveals, the futuredate var is 2 minutes incremented, but that the elem.text() remains the current time.



via Chebli Mohamed

Jquery DataTable filtering without using a global object

I have a datatable that is sometimes shown and sometimes hidden. I also have several other tables on the same page.

The datatables example (located here) uses a global object to store your custom function $.fn.dataTable.ext.search. This is great, it affects all tables.

I can't find a way to provide a search function per table and not add it to a global variable.



via Chebli Mohamed

Select2 is not working in bootstrap modal form

When I am using Select2 in my project creation form that is in the outer loop, it works. The code below is that form.

      <!-- Modal for Creating Project -->
      <div id="createProject" class="modal fade" role="dialog">
        <div class="modal-dialog">
          <!-- Modal content-->
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal">&times;</button>
              <h4 class="modal-title">Create a new project</h4>
            </div>
            <div class="modal-body">
              <form ng-submit="project.createProject()">
                Title: <br>
                <input class="form-control" type="text" name=title ng-model="project.projectData.title" required="true">
                Description: <br>
                <input class="form-control input-lg" type="text" name=description ng-model="project.projectData.description" required="true">
                Assignee: <br> 
                <!-- This is wherer I use Select2 to assign users-->
                <select class="form-control users" id="users" multiple="multiple" style="width: 100%" type="text" ng-model="project.projectData.assigneeID" required="true">
                  <optgroup ng-repeat="eachUser in user.users | filter: search | orderBy: 'lastname' track by $index">
                    <option value="{{eachUser._id}}"> {{eachUser.firstname}} {{eachUser.lastname}} {{eachUser.cname}} </option>
                  </optgroup>
                </select>
                <div class="text-center">
                  <br><button type="button" class="btn btn-default btn-lg" data-dismiss="modal">Cancel</button>
                  <button class="btn btn-primary btn-lg" type="submit">Submit</button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>

JS for this Select2 in the controller:

  $(".users").select2({
    tags: true,
    multiple: true,
    data: true,
    createTag: function(params) {
      return undefined;
    }
  });

However, inside the loop I need to use Select2 many times, and none of them work. By isn't working, it only shows the bootstrap class, but the Select2 class isn't working. Here is one of them don't work:

<!-- Modal for Creating Task -->
<div id="createTask{{eachProject._id}}" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Create a new task</h4>
            </div>
            <div class="modal-body">
                <form ng-submit="task.createTask(eachProject._id)">
                    Title: <br>
                    <input class="form-control" type="text" name=title ng-model="task.taskData.taskTitle" required="true">
                    Description: <br>
                    <input class="form-control input-lg" type="text" name=description ng-model="task.taskData.taskDescription" required="true">
                    Assignee: <br>
                    <!-- This is where I use Select2 -->
                    <select class="form-control createTask_Users <!-- This is where I think is the problem, form-control is working but Select2 is not -->" id="createTask_Users" multiple="multiple" style="width: 100%" type="text" ng-model="task.taskData.assigneeID" required="true">
                        <optgroup ng-repeat="eachUser in user.users | filter: search | orderBy: 'lastname' track by $index">
                            <option value="{{eachUser._id}}"> {{eachUser.firstname}} {{eachUser.lastname}} {{eachUser.cname}} </option>
                        </optgroup>
                    </select>
                    <div class="text-center">
                        <br><button type="button" class="btn btn-default btn-lg" data-dismiss="modal">Cancel</button>
                        <button class="btn btn-info btn-lg" type="submit">Submit</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

And here is the JS for it in the controller:

  $(".createTask_Users").select2({
    tags: true,
    multiple: true,
    data: true,
    createTag: function(params) {
      return undefined;
    }
  });

Is there anything wrong? How come the first one works but the rest don't work?



via Chebli Mohamed

Angularjs data binding issue / javascript being weird

This is undoubtedly a stupid problem where I'm just doing something simple wrong.

I have a page with several directives, loading their templates and controllers. All of which is working fine except for this one.

Using the controller as model, this. is the same as $scope.. So in my controller I have:

var self = this;
this.states = { showControls: false, showVideo: false }

this.showVideo = function() { self.states.showVideo = true; }
this.showControls = function() { self.states.showControls = true; }

$scope.$on(Constants.EVENT.START_WEBCAM, self.showVideo)
$scope.$on(Constants.EVENT.VIDEO_SUCCESS, self.showControls)

In the view I have a button to reveal this part of the view and subsequently request access to your webcam. Clicking the button broadcasts an event with $rootScope.$broadcast from the parent controller.

When the user grants access to the webcam (handled in the directive's link function) it broadcasts another event the same way.

Both methods are triggered by listening with $scope.$on, and both methods fire as they should. However, the showVideo method successfully updates its associated state property, and the showControls method does not. What am I doing wrong?

Using the debug tool it looks like states.showControls is being set to true, but this change isn't reflected in the view, and adding a watcher to the states object doesn't detect any change at this point either. It does when I set showVideo.



via Chebli Mohamed

Select2 dynamic dropdowns with templating

Trying to work out how to use the select2 templating function with a dynamic select2 dropdown to also show the extra data in a JSON response

Example data

{"id":"12","value":"DASGDSA67","otherData":"Brunswick","extraData":"Heads"}

View (Javascript)

<script type="text/javascript">
$(document).ready(function() {
    $(".company2").select2();
    $(".location2").select2({
        templateResult: formatState
    });
});

$(".company2").select2().on('change', function() {
var $company2 = $('.company2');
$.ajax({
    url:"../api/locations/" + $company2.val(),
    type:'GET',
    success:function(data) {
        var $location2 = $(".location2");
        $location2.empty();
        $.each(data, function(value, key) {
            $location2.append($("<option></option>").attr("value", value).text(key));
        }); 
        $location2.select2();
    }
});
}).trigger('change');

function formatState (state) {
  if (!state.id) { return state.text; }
      var $state = $(
         '<h1>' + state.element.value() + '</h1>' + '<p>' + state.element.otherData() + '</p>'
      );
  return $state;
};
</script>



via Chebli Mohamed

TypeError: click called on object that does not implement interface HtmlElement

I've seen the other questions on this topics, but i can't spot the error in my code.

$('#submit_bulk').on('click',function(e){

    var action = $('select[name="bulk_action"]'),
    targets = $('table tr td:first-child :checkbox:checked');
    if(action=='invalid' || targets.length == 0){
        sk.alert('Nothing to do','warning');
        return false;
    }else{
        $(this).html('Working....');

        var fData = {
            action: action,
            mixtapes: '',
            singles: ''
        };

        $.each(targets,function(i,v){
            if($(this).data('type') == 'mixtape'){
                fData.mixtapes += $(this).data('id')+',';
            }else{
                fData.singles += $(this).data('id')+',';
            }
        });

        fData = $.param(fData); 

        console.log(fData); //i get no output here. is fData null?

        $.post(window.location.origin+'/adminAPI/bulk_action',fData,function(data){
            var data = JSON.parse(data);
            if(data.error==0){
                sk.alert('Your changes were saved','success');
                //update view here.
            }else{
                sk.alert(data.message,'error');
            }
        });
        $(this).html('go');
    }

});



via Chebli Mohamed

Copying custom json object to clipboard with javascript

I'm developing a shared canvas using HTML5 + javascript. I am developing copying/pasting functionality, and I have no problems to do it with Ctrl+C, +X, +V, but I also would like to add the typical buttons that provide the same functionality (mainly intended to be able to copy/paste in tablets).

The code to manage the standard events is quite straigtforward:

window.addEventListener("copy", copyFunc);

...

copyFunc(e){
  if (BDKanvasInstance.selection !== null){
    var data = BDKanvasInstance.selection.serialize();
    var jsonData = JSON.stringify(data);
    e.clipboardData.setData('application/json', jsonData);
    e.preventDefault();
  }
}

But I have to way to access the clipboardData from a button...

copyBtn.addEventListener("click", copyBtnFunc);

copyBtnFunc(e){
  /* Any way to access clipboardData or to trigger the standard copy command? */
}

I've seen several solutions involving creating a textarea, inserting the text, selecting it programmatically and using "execCommand('copy')", but that does not copy the text with an "application/json" type...

Any solutions? With a computer using keyboard shortcuts is ok, but they are not a solution when using it on the tablet...

Thank you!



via Chebli Mohamed

Wrap links found in content editable div on user keypress.

How would I go about wrapping text in a content editable div that is a URL right when the user enters it and without changing the position of the cursor? I had this same issue with handling #hashtags and @mentions, but I was able to get passed that by using At.js .



via Chebli Mohamed

How can I redirect to home page after video stops

I am using Cincopa to embed my video into my website. The page that it is embedded in is hidden and navigation is removed. So I would like everyone to be redirected to the home page once the video is finished.

Here is my code:

<div id="cp_widget_55a42f1b-6e51-4738-87f9-eaf52dc6a826">...</div>
<script type="text/javascript">
    var cpo = [];
    cpo["_object"] = "cp_widget_55a42f1b-6e51-4738-87f9-eaf52dc6a826";
    cpo["_fid"] = "AsBAj2M3MQOr";
    var _cpmp = _cpmp || [];
    _cpmp.push(cpo);
    (function() {
        var cp = document.createElement("script");
        cp.type = "text/javascript";
        cp.async = true;
        cp.src = "//www.cincopa.com/media-platform/runtime/libasync.js";
        var c = document.getElementsByTagName("script")[0];
        c.parentNode.insertBefore(cp, c);
    })();
</script>
<noscript>Powered by Cincopa <a href='http://ift.tt/1kTdl6w'>Video Hosting for Business</a> solution.<span>Test</span><span>bitrate</span><span> 39961 kb/s</span><span>height</span><span> 1080</span><span>duration</span><span> 00:02:35.31</span><span>lat</span>:<span> +33.2269</span><span>long</span>:<span> 21-96.93</span><span>fps</span><span> 59.94</span><span>width</span><span> 1920</span><span>originaldate</span><span> 2015-06-06 19:08:58</span>
</noscript>



via Chebli Mohamed

Cannot get WaitForImages to work with angularjs

I'm having problems getting waitforimages to work with angularjs. I have a containing div that contains a div with the ng-repeat directive. Within the repeater is an image. When the angular code executes I will end up with several images on the screen (depending on the number in the underlying model).

I have attached waitforimages to the containing div but although it initialises correctly, nothing happens as the individual images are loaded in.

Is this a known problem using the plugin with angular? I've used it in the past with non-angular projects and it has worked just fine.



via Chebli Mohamed

Selecting an element from an array 35% more often

edited

I have a list with N elements, where K elements are "special" and the rest are "normal". What I'm trying to do is pick an element at random, but special elements should be selected 35% more often than normal items.

For example:

var myList = [
   {id: 1, special: 0},
   {id: 2, special: 1} // <= special item
];

After 600 selections, the normal element should be selected 250 times, and the second should be selected 35% more times than that, or 350 times.

This is different from the suggested duplicate question because my weights do not add up to 1. I can have any arbitrary of elements in my list, and zero or more of them are special. The weight is always .35 for special items, and 0.0 for normal items.



via Chebli Mohamed

Drag And Drop Image to Canvas (FabricJS)

The Problem
I want to do this with an image instead of a canvas object. Meaning you have to add the thing you want to add TO AND AS A PART of the canvas before you can add it. The images are actually part of the website so it doesn't need to do some intricate stuff. This code I found here only works for when it's an object not an actual element. And by the way I'm using FabricJS just to let you know that I'm not using the default HTML5 canvas stuff.

As for any alternatives that are possibly going to work without using my current code. Please do post it down below in the comments or in the answers. I would really love to see what you guys got in mind.

Summary
Basically I want to be able to drag and drop images through the canvas while retaining the mouse cursor position. For example if I drag and image and the cursor was at x: 50 y: 75 it would drop the image to that exact spot. Just like what the code I found does. But like the problem stated the CODE uses an object for you to drag it to the canvas then it clones it. I want this functionality using just plain old elements. E.g: <img>.


THE CODE - JsFiddle

window.canvas = new fabric.Canvas('fabriccanvas');
var edgedetection = 8; //pixels to snap
canvas.selection = false;

window.addEventListener('resize', resizeCanvas, false);

function resizeCanvas() {
    canvas.setHeight(window.innerHeight);
    canvas.setWidth(window.innerWidth);
    canvas.renderAll();
}

// resize on init
resizeCanvas();

//Initialize Everything
init();

function init(top, left, width, height, fill) {

    var bg = new fabric.Rect({
        left: 0,
        top: 0,
        fill:  "#eee",
        width: window.innerWidth,
        height: 75,    
        lockRotation: true,
        maxHeight: document.getElementById("fabriccanvas").height,
        maxWidth: document.getElementById("fabriccanvas").width,
        selectable: false,
    });

    var squareBtn = new fabric.Rect({
        top: 10,
        left: 18,
        width: 40,
        height: 40,
        fill: '#af3',
        lockRotation: true,
        originX: 'left',
        originY: 'top',
        cornerSize: 15,
        hasRotatingPoint: false,
        perPixelTargetFind: true,
    });

    var circleBtn = new fabric.Circle({
        radius: 20,
        fill: '#f55',
        top: 10,
        left: 105,
    });

    var triangleBtn = new fabric.Triangle({
        width: 40, 
        height: 35, 
        fill: 'blue', 
        top: 15,
        left: 190,
    });

    var sqrText = new fabric.IText("Add Square", {
        fontFamily: 'Indie Flower',
        fontSize: 14,
        fontWeight: 'bold',
        left: 6,
        top: 50,
        selectable: false,
    });

    var cirText = new fabric.IText("Add Circle", {
        fontFamily: 'Indie Flower',
        fontSize: 14,
        fontWeight: 'bold',
        left: 95,
        top: 50,
        selectable: false,
    });

    var triText = new fabric.IText("Add Triangle", {
        fontFamily: 'Indie Flower',
        fontSize: 14,
        fontWeight: 'bold',
        left: 175,
        top: 50,
        selectable: false,
    });

    var shadow = {
        color: 'rgba(0,0,0,0.6)',
        blur: 3,    
        offsetX: 0,
        offsetY: 2,
        opacity: 0.6,
        fillShadow: true, 
        strokeShadow: true 
    };

    window.canvas.add(bg);
    bg.setShadow(shadow);
    window.canvas.add(squareBtn);
    window.canvas.add(circleBtn);
    window.canvas.add(triangleBtn);
    window.canvas.add(sqrText);
    window.canvas.add(cirText);
    window.canvas.add(triText);

    canvas.forEachObject(function (e) {
        e.hasControls = e.hasBorders = false; //remove borders/controls
    });

    function draggable(object) {
        object.on('mousedown', function() {
            var temp = this.clone();
            temp.set({
                hasControls: false,
                hasBorders: false,
            });
            canvas.add(temp);
            draggable(temp);
        });
        object.on('mouseup', function() {
            // Remove an event handler
            this.off('mousedown');

            // Comment this will let the clone object able to be removed by drag it to menu bar
            // this.off('mouseup');

            // Remove the object if its position is in menu bar
            if(this.top<=75) {
                canvas.remove(this);
            }
        });
    }

    draggable(squareBtn);
    draggable(circleBtn);
    draggable(triangleBtn);

    this.canvas.on('object:moving', function (e) {
        var obj = e.target;
        obj.setCoords(); //Sets corner position coordinates based on current angle, width and height
        canvas.forEachObject(function (targ) {
            activeObject = canvas.getActiveObject();


            if (targ === activeObject) return;


            if (Math.abs(activeObject.oCoords.tr.x - targ.oCoords.tl.x) < edgedetection) {
                activeObject.left = targ.left - activeObject.currentWidth;

            }
            if (Math.abs(activeObject.oCoords.tl.x - targ.oCoords.tr.x) < edgedetection) {
                activeObject.left = targ.left + targ.currentWidth;

            }
            if (Math.abs(activeObject.oCoords.br.y - targ.oCoords.tr.y) < edgedetection) {
                activeObject.top = targ.top - activeObject.currentHeight;
            }
            if (Math.abs(targ.oCoords.br.y - activeObject.oCoords.tr.y) < edgedetection) {
                activeObject.top = targ.top + targ.currentHeight;
            }
            if (activeObject.intersectsWithObject(targ) && targ.intersectsWithObject(activeObject)) {

            } else {
                targ.strokeWidth = 0;
                targ.stroke = false;


            }
            if (!activeObject.intersectsWithObject(targ)) {
                activeObject.strokeWidth = 0;
                activeObject.stroke = false;
                activeObject === targ
            }
        });
    });
}

CREDITS
Fabric JS: Copy/paste object on mouse down



via Chebli Mohamed

Modify JavaScript Filter to allow dates and multiple selection options combined on each filter rule

I have a JavaScript Filter which allows me to filter out rows (make hidden) from my Task List.

Demo of what I have right now: http://ift.tt/1NtGe72

It currently works with dropdown selection fields and allows multiple filters to be combined.

For example you can filter out every task that doesn't have a Status of Completed and doesn't have a Milestone set to Milestone 3.

It works great thanks to the help creating it from SO user Lucio Paiva on my other question here How to combine multiple FIlters together to filter Task Rows using jQuery?

It looks like this...

enter image description here


I now need to improve upon the features of this code to add some different types of filters besides a simple true/false based on a dropdown selection.

  1. Date Range - I need to add in the ability to filter out rows that dont match a date range. FOr example be able to use a fancy date range selector... enter image description here
  2. Multi-select/checkbox - I also need to be able to select more than 1 item for some of the filter columns. For example on the Milestone column. Be able to select Milestone 2 and Milestone 3 and it would filter out all rows that don't match one of the 2. Image below shows example of GitHub issue which has a filter that allows more than 1 selection on a Label filter. IMage has 3 labels filters selected... enter image description here
  3. With both these new types of filters it needs to still work with the existing dropdown selection filters and still allow multi-filter so that many filters can be set and work together like it currently works.

Below is my code for the filter JS and HTML


JavaScript which filters the Task list rows...

(function () {
  var
    filters = {
      user: null,
      status: null,
      milestone: null,
      priority: null,
      tags: null,
      title: null
    };

  function updateFilters() {
    $('.task-list-row').hide().filter(function () {
      var
        self = $(this),
        result = true; // not guilty until proven guilty

      Object.keys(filters).forEach(function (filter) {
        if (filters[filter] && (filters[filter] != 'None') && (filters[filter] != 'Any')) {
          result = result && filters[filter] === self.data(filter);
        }
      });

      return result;
    }).show();
  }

  function bindDropdownFilters() {
    Object.keys(filters).forEach(function (filterName) {
      $('#' + filterName + '-filter').on('change', function () {
        filters[filterName] = this.value;
        updateFilters();
      });
    });
  }

  bindDropdownFilters();
})();

HTML table of Filters and Tasks which the Filters apply to...

<br><h2>Testing Task List Filters</h2><hr><br>

<div class="container">
  <div class="row">

      <table class="table">
        <thead>
          <tr class="filters">
            <th>
              <input type="text" id="title-filter" value="" class="form-control">
            </th>
            <th>Assigned User
              <select id="user-filter" class="form-control">
                <option>None</option>
                <option>John</option>
                <option>Rob</option>
                <option>Larry</option>
                <option>Donald</option>
                <option>Roger</option>
              </select>
            </th>
            <th>Status
              <select id="status-filter" class="form-control">
                <option>Any</option>
                <option>Not Started</option>
                <option>In Progress</option>
                <option>Completed</option>
              </select>
            </th>
            <th>Milestone
              <select id="milestone-filter" class="form-control">
                <option>None</option>
                <option>Milestone 1</option>
                <option>Milestone 2</option>
                <option>Milestone 3</option>
              </select>
            </th>
            <th>Priority
              <select id="priority-filter" class="form-control">
                <option>Any</option>
                <option>Low</option>
                <option>Medium</option>
                <option>High</option>
                <option>Urgent</option>
              </select>
            </th>
            <th>Tags
              <select id="tags-filter" class="form-control">
                <option>None</option>
                <option>Tag 1</option>
                <option>Tag 2</option>
                <option>Tag 3</option>
              </select>
            </th>
          </tr>
        </thead>
      </table>


    <div class="panel panel-primary filterable">
      <div class="panel-heading">
        <h3 class="panel-title">Tasks</h3>
        <div class="pull-right"></div>
      </div>





      <table id="task-list-tbl" class="table">
        <thead>
          <tr>
            <th>Title</th>
            <th>Created</th>
            <th>Due Date</th>
            <th>Priority</th>
            <th>Milestone</th>
            <th>Assigned User</th>
            <th>Tags</th>
          </tr>
        </thead>

        <tbody>

          <tr id="task-1"
              class="task-list-row" 
              data-task-id="1"
              data-title="Task title 1"
              data-user="Larry"
              data-status="In Progress"
              data-milestone="Milestone 2"
              data-priority="Urgent"
              data-tags="Tag 2">
            <td>Task title 1</td>
            <td>01/24/2015</td>
            <td>09/24/2015</td>
            <td>Urgent</td>
            <td>Milestone 2</td>
            <td>Larry</td>
            <td>Tag 2</td>
          </tr>

          <tr id="task-2"
              class="task-list-row" 
              data-task-id="2"
              data-title="Task title 2"
              data-user="Larry"
              data-status="Not Started"
              data-milestone="Milestone 2"
              data-priority="Low"
              data-tags="Tag 1">
            <td>Task title 2</td>
            <td>03/14/2015</td>
            <td>09/18/2015</td>
            <td>Low</td>
            <td>Milestone 2</td>
            <td>Larry</td>
            <td>Tag 1</td>
          </tr>

          <tr id="task-3"
              class="task-list-row" 
              data-task-id="3"
              data-title="Task title 3"
              data-user="Donald"
              data-status="Not Started"
              data-milestone="Milestone 1"
              data-priority="Low"
              data-tags="Tag 3">
            <td>Task title 3</td>
            <td>11/16/2014</td>
            <td>02/29/2015</td>
            <td>Low</td>
            <td>Milestone 1</td>
            <td>Donald</td>
            <td>Tag 3</td>
          </tr>


          <tr id="task-4"
              class="task-list-row" 
              data-task-id="4"
              data-title="Task title 4"
              data-user="Donald"
              data-status="Completed"
              data-milestone="Milestone 1"
              data-priority="High"
              data-tags="Tag 1">
            <td>Task title 4</td>
            <td>11/16/2014</td>
            <td>02/29/2015</td>
            <td>High</td>
            <td>Milestone 1</td>
            <td>Donald</td>
            <td>Tag 1</td>
          </tr>

          <tr id="task-5"
              class="task-list-row" 
              data-task-id="5"
              data-title="Task title 5"
              data-user="Donald"
              data-status="Completed"
              data-milestone="Milestone 3"
              data-priority="High"
              data-tags="Tag 1">
            <td>Task title 5</td>
            <td>11/16/2014</td>
            <td>02/29/2015</td>
            <td>High</td>
            <td>Milestone 3</td>
            <td>Donald</td>
            <td>Tag 1</td>
          </tr> 

          <tr id="task-6"
              class="task-list-row" 
              data-task-id="6"
              data-title="Task title 6"
              data-user="Donald"
              data-status="Completed"
              data-milestone="Milestone 2"
              data-priority="High"
              data-tags="Tag 3">
            <td>Task title 6</td>
            <td>11/16/2014</td>
            <td>02/29/2015</td>
            <td>High</td>
            <td>Milestone 2</td>
            <td>Donald</td>
            <td>Tag 3</td>
          </tr>


          <tr id="task-7"
              class="task-list-row" 
              data-task-id="7"
              data-title="Task title 7"
              data-user="Donald"
              data-status="Completed"
              data-milestone="Milestone 1"
              data-priority="High"
              data-tags="Tag 1">
            <td>Task title 7</td>
            <td>11/16/2014</td>
            <td>02/29/2015</td>
            <td>High</td>
            <td>Milestone 1</td>
            <td>Donald</td>
            <td>Tag 1</td>
          </tr>

        </tbody>
      </table>
    </div>
  </div>
</div>



via Chebli Mohamed