foreach is not function,how to solve this? js [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
i building caraousel container but there is a problem in this part.
enter image description here
span class="cursor1" id="cursor1">❮</span>
<span class="cursor2" id="cursor2">❯</span>
<div class="kategori-container">
<div class="border-box" id="border-box" >
<div class="kategori-item">
<div class="thumbler-bg"></div>
<div class="produk-thumbler">
<img class="thumbler-img" src="feature/images__15_-removebg-preview.png" alt="" srcset="">
<div class="kategori-text">
<span>produk kucing</span>
</div>
</div>
</div>
</div>
const featureContainers = [...document.querySelectorAll('.border-box')];
// console.log(featureContainers)
const cursorRight = [...document.querySelectorAll('.cursor1')];
const cursorLeft = [...document.querySelectorAll('.cursor2')];
featureContainers[0].forEach((objek, ruang) => {
let featureDimensions = objek.getBoundingClientRect();
let featureWidth = featureDimensions.width;
// console.log(ruang);
cursorRight[ruang].addEventListener('click', () => {
objek.scrollLeft += featureWidth;
})
cursorLeft[ruang].addEventListener('click', () => {
objek.scrollLeft -= featureWidth;
})
});
i'm stuck here,can someone help me?

forEach runs on array.. you are invoking it on first element using [0]
so instead of
featureContainers[0].forEach
do
featureContainers.forEach

Related

How can I set a data attribute on an element? [duplicate]

This question already has answers here:
How do I dynamically set HTML5 data- attributes using react?
(2 answers)
Closed 2 years ago.
Silly question but...
I have a div which looks like this:
<div class="container">
<div class="abc" />
<div class="abc" />
<div>
Can I set the value for the div.abc like this <div class="abc" value={2}></div>? And then use js to calculate the total by iterate through the child of div.container?
EDIT: as isherwood mentioned in the comments. This answer is just javascript solution and not specific for reactjs as I missed that question had reactjs tag. See recommended answer How do I dynamically set HTML5 data- attributes using react? for better solution!
You probably looking for html data attribute
<div class="container">
<div data-your-prop="1" />
<div data-your-prop="1.5" />
<div data-your-prop="2" />
<div>
e.g. 1
const divs = document.querySelectorAll('.container div[data-your-prop]')
divs.forEach(function (el, index) {
console.log(el.dataset.yourProp)
})
e.g. 2
const divs = document.querySelectorAll('.container div[data-your-prop]')
let totalInt = 0
let totalFloat = 0
divs.forEach(function (el, index) {
totalInt += parseInt(el.dataset.yourProp)
totalFloat += parseFloat(el.dataset.yourProp)
});
console.log(totalInt)
console.log(totalFloat.toFixed(2))
// yields
//
// 4
// "4.50"
note
(data-) attribute names are attached to el.dataset and names defined in dom are normalized to be valid json property.

How to write this code cleaner, without repetition? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
$("#yl").click(function(){updateYear("sub")});
$("#yr").click(function(){updateYear("add")});
$("#ml").click(function(){updateMonth("sub")});
$("#mr").click(function(){updateMonth("add")});
$("#dl").click(function(){updateDay("sub")});
$("#dr").click(function(){updateDay("add")});
Is there a way to write this code cleaner, smarter without repetitions?
If you change your elements a bit, you could do something like this:
<button id='yr' data-type='update' data-date-part='year' data-date-action='add'>
Then you create an update function that starts off like this:
function update() {
const el = $(this);
const datePart = el.attr('data-date-part');
const dateAction = el.attr('data-date-action');
// do your logic to update the date based on what part and action
}
Then your click handler just needs to be:
$('button[data-type="update"]').click(update);
I forgot to mention, that newer versions of jquery will also let you just use the .data() function instead of spelling out the full data- attribute
The code is fine as it stands as it is very clear what is happening.
If you really want to do it differently, then you should probably also modify your function(s) and look into HTML attributes. It all depends what you are actually doing in those functions.
If for instance you want the user to enter a date just by pressing add/sub buttons, then the basics could look like this:
$('.change-value').click(updateDatePart);
function updateDatePart() {
// Read current date
var dateParts = $.map($(this).closest(".dateinput").find(".part-value"), function (span) {
return +$(span).text();
});
// Which part of the date needs incrementing/decrementing?
var part = $(this).closest('.part').index();
// Apply change to that part
dateParts[part] += $(this).data("inc");
// Create a date with this
var date = new Date(dateParts[0], dateParts[1]-1, dateParts[2]);
// Get the parts for the new date (which may have resolved some overflow)
dateParts = [date.getFullYear(), date.getMonth()+1, date.getDate()];
// Output the result
$('.part-value').each(function (i, elem) {
$(elem).text(dateParts[i]);
});
}
.change-value { font-size: 50% }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="dateinput">
<span class="part">
<button class="change-value" data-inc="-1">-</button>
<span class="part-value">2017</span>
<button class="change-value" data-inc="1">+</button>
</span>-
<span class="part">
<button class="change-value" data-inc="-1">-</button>
<span class="part-value">12</span>
<button class="change-value" data-inc="1">+</button>
</span>-
<span class="part">
<button class="change-value" data-inc="-1">-</button>
<span class="part-value">24</span>
<button class="change-value" data-inc="1">+</button>
</span>
</span>

AngularJs/Javascript , Copy Object is good practice? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
i'm wrote some todo list app, to understand how to be more expert.
what i'm try to understand:
my problem is when user click on task to edit, because it passed by reference so if user edit task, it will change directly the task object.
(i attached my code here).
my questions:
1) in my code i wrote one way to fix it, by clone object every time.
it good practice ? if no how you recommend me to fix it?
2) because i do not want my code only work, i want to be more expert.
if you think my thinking and planning of this code is bad? how you write this app? ( i talk here only about functional, add, edit, list of task)
thanks for help :)
link to plunker: https://plnkr.co/edit/CA99iiydbD4TWaGtJZZf?p=preview
code:
HTML
<html ng-app="todos">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="main">
<ul>
<li ng-repeat="task in todosBL.tasks" ng-click="editMode.edit(task)">{{ task.content}}</li>
</ul>
<input type="text" ng-model="task">
<input type="button" value="add task" ng-click="add(task)">
<!--//for edit-->
<div>
<input type="text" ng-model="editMode.task.content">
<input type="button" value="save task" ng-click="editMode.save(editMode.task)">
</div>
</div>
</body>
</html>
SCRIPT:
(function() {
var Task = (function() {
var counter = 0;
return function(content, isDone) {
this.id = counter++;
this.content = content;
this.isDone = isDone || false;
}
}());
var app = angular.module('todos',[])
.service('todosBL', function() {
this.tasks = [];
this.add = function(content) {
this.tasks.push(new Task(content));
}
this.update = function(editedTask) {
var i = this.tasks.findIndex(function(task){
return task.id === editedTask.id
});
this.tasks[i] = editedTask;
}
})
.controller('main', function($scope, todosBL) {
$scope.todosBL = todosBL;
$scope.add = function(task) {
todosBL.add(task);
$scope.task = null;
}
$scope.editMode = {
task: {},
edit: function(task) {
this.task = task;
//BECAUSE I PASS TASK BY REFERNCE WHEN USER EDIT TASK IT CHANGE TASK DIRECTLY ,
// IF I CLONE OBJECT EVERY TIME, IT FIX BY REFERENCE PROBLEM.
// MY QUESTION IF HAVE OTHER WAY TO SLOVE THIS. MABY OTHER WAY TO THINK ABOUT APP LIKE THIS.
// for(key in task) {
// this.task[key] = task[key];
// }
},
save: function(task) {
todosBL.update(task);
this.task = {};
}
};
});
}());
I think that your controller is over complicated. The service should implement some BL like data verification and posting it to the server and/or local storage but not searching for index, it does silly things now!
In order to satisfy all your requirements one just needs a controller:
app.controller('MainCtrl', function($scope) {
$scope.tasks = [];
$scope.add = function(content){
$scope.tasks.push(new Task(content));
$scope.content = null;
}
$scope.edit = function(task){
$scope.currentlyEditing = task;
$scope.editText = task.content;
}
$scope.save= function(){
$scope.currentlyEditing.content = $scope.editText;
$scope.editText = null;
$scope.currentlyEditing = null;
mySuperSeriousService.postToServer.then(result=> {
alert('Success');
})
}
});
and template like this:
<body ng-controller="MainCtrl">
<ul>
<li ng-repeat="task in tasks" ng-click="edit(task)">{{ task.content}}</li>
</ul>
<input type="text" ng-model="content">
<button ng-click="add(content)">Add Task</button>
<!--//for edit-->
<div>
<input type="text" ng-model="editText" ng-disabled="!currentlyEditing">
<button ng-click="save()">Save</button>
</div>
</body>
So it's 2 times shorter. Here's the plunker (https://plnkr.co/edit/nN8kd5ErSDsBu6Exm1YO)
my problem is when user click on task to edit, because it passed by reference so if user edit task, it will change directly the task object. (i attached my code here).
For solving this problem, you should make a copy of your model and change it (in edit function): this.task = angular.copy(task);
in my code i wrote one way to fix it, by clone object every time. it good practice ? if no how you recommend me to fix it?
As I said, making copy is much more logical !
because i do not want my code only work, i want to be more expert. if you think my thinking and planning of this code is bad? how you write this app? ( i talk here only about functional, add, edit, list of task)
1) I don't know why you are using an array of objects ? your tasks are just strings ! so it can be better if you use an array of strings. then you won't have the struggle with sth like editMode.task.content, you just use editMode.task !
2) Don't work with ids . cause when you add the 'Deleting Task' feature, you'll got problems ...
3) What does Task() function do ? ( In this case, you don't need sth like this)
4) ...

Javascript global variable is undefined,why? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
hello please take a look at my code below
var vsize; //global variable
function veg7() {
vsize = 7;
}
function veg10() {
vsize = 10;
}
function getCBP() {
if (vsize == 7) {
alert(vsize);
} else {
alert(vsize);
}
}
<input type="button" onclick="getCBP()" value="getCBP()">
<div class="main-menu">
<ul style="padding-left:13px; position:relative;top:41px;margin-bottom:0px;">
<li>
7" Veg
</li>
<li>
10" Veg
</li>
<li>
7" Non Veg
</li>
<li>
10" Non Veg
</li>
<li>
Pizaxx
</li>
<li>
Side Orders
</li>
</ul>
</div>
if any event access the function veg7() or function veg10() (it is dynamic) and changes the value of vsize accordingly then why am i getting vsize as undefined.
please help me..i need the value of vsize in getCBP().
It is undefined, but declared.
You are executing your function before assigning a value to your variable vsize.
you should declare var vsize = 0 (or any value), or run one of your veg functions before running getCBP.
Try var vsize = -1;
If you now see -1 instead of undefined, that means your functions are never called.
Note: I'm using -1 because that's easier to spot as an "error" than 0.

create this HTML markup with Javascript ( a complex DL entry of Dt and DD) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Dear Friends of StackOverflow,
I need to make the following HTML markup entry to a definition list "DL" thru Javascript so i can make the entry dynamically. Also need to edit the CSS Values. I will put the CSS entry after the HTML. In the dd entry there is a class, an anchor with class, an href, some text, another anchor with class, and href. I don't know the proper syntax to enter these thru Javascript. Many thanks for any help. Markandeya
<dt class="Book2"><span>Book2</span></dt>
<dd class="Book2"><a class="amazonLink" href="http://www.amazon.co.uk/Principles-Beautiful-Web-Design/dp/0975841963%3FSubscriptionId%3DAKIAJCFYSPA5V4ZSCM6Q%26tag%3Dstevwork-21%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D0975841963"><img src="http://ecx.images-amazon.com/images/I/41FxC9u%2B%2BVL._SL160_.jpg" alt=""></a><br>
<strong>Beautiful Web Design</strong> by Jason Beaird.<br>
This book teaches you a wide range of topics on how to make great web sites, covering layout styles, ratios and colour theory.<br>
<a class="publisherLink" href="#">Beautiful Web Design on SitePoint</a>
</dd>
CSS hard code for the class "Book2" is: ( need syntax to edit entries thru Javascript)
dl.bookshelf dt.Book2 {
background: url(img/beautdesign-spine.png) 0 0 no-repeat,
url(img/beautdesign-front.png) 40px 0 no-repeat;
left:52px;
width:280px;
z-index:2;
}
Not exactly the same style output. The publisher field can be left off, and an image is not required for the store link. You can also set the class from the JSON object for the store link. The desc is an array, which is converted into a series of paragraphs. This may not be exactly what you want, but it should at least provide a good running start.
First, the Javascript:
var books = [
{
title: 'Beautiful Web Design',
author: 'Jason Beaird',
link: {
cls: 'amazonLink',
href: 'http://www.amazon.co.uk/Principles...',
img: 'http://ecx.images-amazon.com/images/...',
text: 'View on Amazon'
},
publisher: {
href: '#',
name: 'SitePoint'
},
desc: [
'This book teaches you...'
]
}
];
var bookshelf = document.getElementById('bookshelf');
for(var i=0,l=books.length;i<l;i++) {
var book = books[i];
var dt = document.createElement('dt');
var title = document.createElement('strong');
title.appendChild(document.createTextNode(book.title));
dt.appendChild(title);
dt.appendChild(document.createTextNode(' by ' + book.author));
var dd = document.createElement('dd');
if(book.link.href !== null) {
var link = document.createElement('a');
link.setAttribute('class',book.link.cls);
link.setAttribute('href',book.link.href);
if(book.link.img !== undefined && book.link.img !== null) {
var img = document.createElement('img');
img.setAttribute('src',book.link.url);
img.setAttribute('alt',book.link.text);
link.appendChild(img);
}
else {
link.appendChild(document.createTextNode(book.link.text));
}
dd.appendChild(link);
}
if(book.desc !== undefined && book.desc instanceof Array) {
for(var j=0,k=book.desc.length;j<k;j++) {
var p = document.createElement('p');
p.appendChild(document.createTextNode(book.desc[j]));
dd.appendChild(p);
}
}
if(book.publisher !== undefined) {
var pub = document.createElement('a');
pub.setAttribute('class','publisherLink');
pub.setAttribute('href',book.publisher.href);
pub.appendChild(document.createTextNode(book.title + ' on ' + book.publisher.name));
dd.appendChild(pub);
}
bookshelf.appendChild(dt);
bookshelf.appendChild(dd);
}
Next, the HTML output:
<dl id="bookshelf">
<dt>
<strong>Beautiful Web Design</strong> by Jason Beaird
</dt>
<dd>
<a class="amazonLink" href="..."><img src="..." alt="View on Amazon"/></a>
<p>
This book teaches you...
</p>
<a class="publisherLink" href="#">Beautiful Web Design on SitePoint</a>
</dd>
</dl>
You can probably add classes and elements here or there to make the resultant HTML more descriptive and more responsive to CSS.

Categories