Calling a function at setInterval Jscript - timer

i have a image slider, and i am wanting to call the fader function at the end of the timer, unfortunately, im a complete novice and only seem to be NOT LEARNING from my mistakes... I know im floating in a boat full of the same kind ,So please could a good sailor divert this boat in the right direction for us. We would all be most great-full of your service..
I have code here, If anybody can explain where im going wrong i would be very happy. Thank you
<script>
function fader (){
var element = document.getElementById("dynamic-image");
element.style.transitionDuration = "2s";
<!---the grabbed element + style [ execute type of effect ] = ' dimension of effect (1 ,2)';--->
element.style.opacity=0;
}
</script>
<script>
(function() {
'use strict';
var preloads=[],c,
d=document,di=d.getElementById('dynamic-image'),
dh=d.getElementById('dynamic-href'),
url=[
'linkmywebsite.ml','chatmagbingo.com','ilkestonwebdesign.com','ipost.com','happypetsuk.com','www.linkmywebsite.co.uk'
];
function preload(){
for(c=0;c<arguments.length;c++) {
preloads[preloads.length]=new Image();
preloads[preloads.length-1].src=arguments[c];
}
c=0;
}
preload('yournewsite2.png','1ad.jpg','2ad.jpg',
'3ad.jpg','4ad.jpg','5ad.jpg');
setInterval(
function starttimer() {
dh.href='http://'+url[c];
di.src=preloads[c].src;
di.alt=preloads[c].src.substring(preloads[c].src.lastIndexOf('/')+1);
c++;
if(c==preloads.length) {
c=0;
}
},5000);
}());
Not sure where to call the function Fader. thank you....

Here is the answer..... again i figure it out...lol
So heres a image fader for that boatfull of novices...simplified.....
<style type="text/css">
.dynamic-image {
position:absolute;
left:0%;
top:0%;
width:100%;
height:100%;
</style>
<img id="dynamic-image" class="dynamic-image" src="ebayad.png";>
<script>
function fader (){
var element = document.getElementById("dynamic-image");
element.style.transitionDuration = "2s";
<!---the grabbed element + style [ execute type of effect ] = ' dimension of effect (1 ,2)';--->
element.style.opacity=4;
}
</script>
<script>
function fader2 (){
var element = document.getElementById("dynamic-image");
element.style.transitionDuration = "2s";
<!---the grabbed element + style [ execute type of effect ] = ' dimension of effect (1 ,2)';--->
element.style.opacity=0;
}
</script>
<script>
setInterval( fader2, 4000 );
(function() {
'use strict';
var preloads=[],c,
di=document.getElementById('dynamic-image');
function preload(){
for(c=0;c<arguments.length;c++) {
preloads[preloads.length]=new Image();
preloads[preloads.length-1].src=arguments[c];
}
c=0;
}
preload('yournewsite2.png','1ad.jpg','2ad.jpg',
'3ad.jpg','4ad.jpg','5ad.jpg');
setInterval( fader, 8000 );
setInterval(
function starttimer() {
di.src=preloads[c].src;
c++;
if(c==preloads.length) {
c=0;
}
},8000);
}());
</script>

Related

Swapping data on ui-grid take a lot of time

I have one grid and according to some conditions, I have to change the data which comes from the back-end.The first time I load data from the back the grid works fine. When I start switching data the grid displays new data well but stays frozen for a while. I notice that this time is random and is often about 3 seconds or plus.
I tried to assign data to the grid through different ways but the result is the same:
1)
$scope.gridOptions = {
//some options,
data: $scope.myData
}
And then
Demande.query({lb: condition}, function (result) {
$timeout(function () {$scope.myData = result;},0);// I also try without $timeout
}
2) I try to assign the data directly to the grid
Demande.query({lb: condition}, function (result) {
$timeout(function () {$scope.gridOptions.data = result;},0);
}
3) I combine the above approachs with
a) $scope.gridApi.core.notifyDataChange(uiGridConstants.dataChange.ROW)
b) $scope.gridApi.core.refreshRows()
but the problem persists. I am using angular-ui-grid 4.0.1
Any idea will be appreciated.
Another option:
4) $scope.gridOptions.data = angular.copy($scope.myData);
Should give the grid the little time that it needs to breath!
Update:
angular.module('app', ['ui.grid'])
.controller('MainCtrl', ['$scope', function($scope) {
$scope.gridOptions = {
columnDefs: []
}
for (var i = 0; i < 80; i++) {
$scope.gridOptions.columnDefs.push({
name: 'C' + (i + 1),
enableColumnMenu: false
});
}
var dataLoadCounter = 1;
$scope.switchData = function() {
$scope.gridOptions.data = [];
for (var i = 0; i < 1000; i++) {
$scope.gridOptions.data.push({});
for (var j = 0; j < 80; j++) {
$scope.gridOptions.data[i]['C' + (j + 1)] = 'D' + dataLoadCounter + (j + 1);
}
}
dataLoadCounter++;
}
$scope.switchData();
}]);
div[ui-grid] {
width: 4500px;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-grid/4.0.2/ui-grid.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/angular-ui-grid/4.0.2/ui-grid.min.css" />
<div ng-app="app" ng-controller="MainCtrl">
<button ng-click="switchData()">Switch Data</button>
<div ui-grid="gridOptions">
</div>
</div>

Incrementally add date with ng-repeat

I have a variable $scope.date in my controller. In the view, I do ng-repeat over a couple of items. Each item has a duration in minutes. How would I go about to incrementally add time for every repeat and display this?
Add a function on the controller that calculates the date including the duration. Working code snippet:
var app = angular.module('myapp', []);
app.controller('myctrl', function($scope) {
$scope.someDate = new Date();
$scope.durations = [1, 2, 5, 6, 8];
$scope.calculateIncrementalDuration = function(index) {
var sum = 0;
for (var i = 0; i <= index; i++) {
sum += $scope.durations[i];
}
return sum;
}
$scope.calculateEndDate = function(startDate, index) {
return new Date(startDate.getTime() + $scope.calculateIncrementalDuration(index) * 60000);
}
});
.delay {
margin-top: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="myctrl">
Start time: {{someDate.toUTCString()}}
<div class="delay" ng-repeat="duration in durations">Duration in minutes: {{calculateIncrementalDuration($index)}}
<div>End time: {{calculateEndDate(someDate, $index).toUTCString()}}</div>
</div>
</div>
I don't have the reputation for a comment, so please don't be angry at me, those who get angry at non-answers as answers, but I would highly recommend looking into moment.js for things like this.

Change icon on click using angular-google-maps

I have a number of markers on a map using angular-google-maps.
Can someone please tell me how to you change the icon image of a marker when you click on it?
My HTML looks like this:
<div class="map-wrapper" flex>
<ui-gmap-google-map flex center='map.center' zoom='map.zoom' class="ui-gmap-google-map" control="control">
<ui-gmap-markers models="markers" coords="'self'" icon="'icon'" doRebuildAll="true"></ui-gmap-markers>
</ui-gmap-google-map>
</div>
My controller code to populate markers:
function mapFilter(dealerList) {
angular.forEach(dealerList, function (dlr) {
if (dlr.Category_type_id == $scope.categoryType) {
var marker = {
id: dlr.Site_owner_id + "_" + dlr.Site_locationseq,
icon: "/img/dealerlocator/pin_icon.png",
events: {
click: function (marker, eventName, model, arguments) {
gotoAnchor(marker.key);
}
},
latitude: dlr.Site_address_map_latitude,
longitude: dlr.Site_address_map_longitude,
showWindow: false
};
$scope.markers.push(marker);
}
});
}
function gotoAnchor(x) {
var newHash = 'anchor_' + x;
if ($location.hash() !== newHash) {
// set the $location.hash to `newHash` and
// $anchorScroll will automatically scroll to it
$location.hash('anchor_' + x);
// Update the map marker icons
angular.forEach($scope.markers, function (mkr) {
if (mkr.id == x) {
mkr.icon = "/img/dealerlocator/pin_icon_selected.png";
} else {
mkr.icon = "/img/dealerlocator/pin_icon.png";
}
});
expandDealer(x);
} else {
// call $anchorScroll() explicitly,
// since $location.hash hasn't changed
$anchorScroll();
expandDealer(x);
}
};
In the gotoAnchor function above, you can see here that I've changed the icon in the markers, but this doesn't change on the map.
You'll need to debug your ($location.hash() !== newHash) to see if its making it through to the forEach. This plunker demo implements the method below, and the icons are updating on click;
function gotoAnchor(x) {
// Update the map marker icons
angular.forEach($scope.randomMarkers, function (mkr) {
if (mkr.id == x) {
mkr.icon = "https://mapicons.mapsmarker.com/wp-content/uploads/mapicons/shape-default/color-ffc11f/shapecolor-color/shadow-1/border-dark/symbolstyle-white/symbolshadowstyle-dark/gradient-no/cserkesz_ikon.png";
} else {
mkr.icon = 'https://mapicons.mapsmarker.com/wp-content/uploads/mapicons/shape-default/color-128e4d/shapecolor-color/shadow-1/border-dark/symbolstyle-white/symbolshadowstyle-dark/gradient-no/crow2.png';
}
});
};

how to wrap text in angularjs and save the position

I would like to wrap text with span tag and save the position.
I know how to do it with JS but i dont know how to do it with angularjs
Here is what i have done:
http://jsfiddle.net/ymeaL06j/1/
This function gives me the position of the text in the DIV
function getSelectionPosition() {
var range = window.getSelection().getRangeAt(0);
var preSelectionRange = range.cloneRange();
preSelectionRange.selectNodeContents(document.getElementById("code"));
preSelectionRange.setEnd(range.startContainer, range.startOffset);
var start = preSelectionRange.toString().length;
return {
start: start,
end: start + range.toString().length
}
};
I take the start and end positions and insert them as an attribute in the span tag
After this i would like to save all the marked positions and load it later, i have a function that select text and then i can wrap it (i hope that there is a better solution)
function setSelection(savedSel) {
var charIndex = 0, range = document.createRange();
range.setStart(document.getElementById("code"), 0);
range.collapse(true);
var nodeStack = [containerEl], node, foundStart = false, stop = false;
while (!stop && (node = nodeStack.pop())) {
if (node.nodeType == 3) {
var nextCharIndex = charIndex + node.length;
if (!foundStart && savedSel.start >= charIndex && savedSel.start <= nextCharIndex) {
range.setStart(node, savedSel.start - charIndex);
foundStart = true;
}
if (foundStart && savedSel.end >= charIndex && savedSel.end <= nextCharIndex) {
range.setEnd(node, savedSel.end - charIndex);
stop = true;
}
charIndex = nextCharIndex;
} else {
var i = node.childNodes.length;
while (i--) {
nodeStack.push(node.childNodes[i]);
}
}
}
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
You can use the same code that you illustrated above and put it inside of your angularjs controller.
Refer to my plunker code; it is a simple angularjs version of your jsfiddle code.
For example, suppose that a snippet of the index.html looks like this:
<body ng-controller="MainCtrl">
<div id="code">This is <b>some text</b> bla bla bla</div>
<br />
<input type="button" value="Mark!" ng-click="markText()" />
<input type="button" value="Remove marks!" ng-click="removeMarks()" />
</body>
Then the example angularjs controller, MainCtrl, could look like this:
app.controller('MainCtrl', function($scope) {
var getSelectionPosition = function () {
var range = window.getSelection().getRangeAt(0);
var preSelectionRange = range.cloneRange();
preSelectionRange.selectNodeContents(document.getElementById("code"));
preSelectionRange.setEnd(range.startContainer, range.startOffset);
var start = preSelectionRange.toString().length;
return {
start: start,
end: start + range.toString().length
}
}
$scope.markText = function() {
var currPosition = getSelectionPosition();
var selection = window.getSelection().getRangeAt(0);
var selectedText = selection.extractContents();
var span = document.createElement("span");
span.className = "Mark";
span.setAttribute("PosStart", currPosition.start);
span.setAttribute("PosEnd", currPosition.end);
span.appendChild(selectedText);
selection.insertNode(span);
};
$scope.removeMarks = function() {
$(".Mark").each(function () {
$(this).contents().unwrap();
});
};
});
Notice that the MainCtrl is the angularjs controller for the body. The ng-click on the buttons reference the markText and removeMarks functions in the controller's scope. The logic in the functions are exactly the same as you referenced in your question (and jsfiddle).
None of your JS code changed other than moving the functions inside of the controller. Again, check out the plunker above to see the actual code working.

Moving angularJS elements created by ng-repeat

I'm trying to move elements that are created by a ng-repeat into some columns. I successfully did it with a directive, but the problem happens when I sort the array of objects on which ng-repeat operates. The directive that searches for the smallest column and then insert the element in it fails to determine the smallest column (maybe because there are still elements in the columns).
I believe the structure I use (directives / controllers etc...) isn't optimal, and I cannot find how to organize the angular code to get the behavior I want.
Here is a jsFiddle showing what I have now : http://jsfiddle.net/kytXy/6/ You can see that the items are being inserted correctly inside the columns. If you click on a button that re-arranges the sorting, then they are not inserted again. If you click multiple times on a same button, watch what happens...
I put commented alerts that you can uncomment so that you can see how items are being inserted and what is wrong. I've also tried emptying the columns before inserting again (commented js in the jsfiddle), whithout any success.
Here is the code :
HTML:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<div ng-app="myModule">
<div ng-controller="Ctrl" >
<button ng-click="predicate = 'id'; reverse=false; setupColumns()">Sort ID</button>
<button ng-click="predicate = 'id'; reverse=true; setupColumns()">Sort ID reversed</button>
<div id="columns" generate-sub-columns post-render>
</div>
<div class="elements">
Elements are stored here !
<div class="element" ng-repeat="(key,elt) in elts | orderBy:predicate:reverse" id="element{{key}}">
Text: {{elt.a}}
</div>
</div>
</div>
</div>
JS:
var myModule = angular.module('myModule', []);
myModule.controller('Ctrl', function($scope) {
$scope.predicate='id';
$scope.reverse=false;
$scope.elts = [
{id:0,a:"Hi man !"},
{id:1,a:"This is some text"},
{id:2,a:"Wanted to say hello."},
{id:3,a:"Hello World!"},
{id:4,a:"I love potatoes :)"},
{id:5,a:"Don't know what to say now. Maybe I'll just put some long text"},
{id:6,a:"Example"},
{id:7,a:"Example2"},
{id:8,a:"Example3"},
{id:9,a:"Example4"},
{id:10,a:"Example5"},
{id:11,a:"Example6"}
];
$scope.setupColumns = function() {
console.log('calling setupColumns');
var eltIndex = 0;
var element = jQuery("#element0");
/*while(element.length > 0) {
jQuery('#elements').append(element);
eltIndex++;
element = jQuery("#element"+eltIndex);
alert(1);
}
alert('Columns should be empty');*/
element = jQuery("#element0");
eltIndex = 0;
var columnCount = 0;
while (jQuery("#column"+columnCount).size() >0)
columnCount++;
while(element.length > 0) {
console.log('placing new element');
var smallestColumn = 0;
var smallestSize = jQuery("#columns").height();
for (var i = 0; i < columnCount; i++) {
var columnSize = jQuery(".column#column"+i).height();
if (columnSize < smallestSize) {
smallestColumn = i;
smallestSize = columnSize;
}
};
jQuery('.column#column'+smallestColumn).append(element);
eltIndex++;
element = jQuery("#element"+eltIndex);
//alert(1);
}
//alert('Columns should be filled');
};
});
myModule.directive('generateSubColumns', function() {
return {
restrict: 'A',
controller: function() {
var availableWidth = jQuery("#columns").width();
var sizePerColumn = 100;
var nbColumns = Math.floor(availableWidth/sizePerColumn);
if (nbColumns<=1)
nbColumns=1;
for (var i = 0; i < nbColumns; i++) {
jQuery('<div class="column" id="column'+i+'">Column '+i+'</div>').appendTo('#columns');
};
}
};
});
myModule.directive('postRender', [ '$timeout', function($timeout) {
var def = {
restrict: 'A',
terminal: true,
transclude: true,
link: function(scope, element, attrs) {
$timeout(scope.setupColumns, 0);
}
};
return def;
}]);
and some css:
#columns {
width: 100%;
}
.column {
width: 100px;
display:inline-block;
vertical-align: top;
border: 1px solid black;
}
.element {
border: 1px solid red;
}
How can I fix that ?
Thanks in advance,
hilnius
First.. Why you are doing something like this?
var element = jQuery("#element0");
Inside a controller?
That kind of code (DOM manipulation) should go inside link function directive and use the $element parameter to access to DOM element.
Also.. What if you use the column-count property to divide your container? https://developer.mozilla.org/es/docs/Web/CSS/column-count

Resources