How to change an object attribute in JavaScript - javascript

I want to change a boolean attribute of an object in JavaScript (the object is from a library called fullPage.js). I want to change the navigation attribute to false, preferably from another file.
Thanks in advance

pretty straight forward. after you create the object just change the value for the key. If you want to do it from a file you have several ways of doing this.
place the object first in local storage
store the object on your backend
place the object as a data element in your html
Show us what you've done so far
let fullpage = {autoscrolling:true,
navagation:true}
console.log(fullpage)
fullpage.navagation = false
console.log(fullpage)

Related

Get object by HTML tag and remove from localstorage

this is my first question on stackoverflow.
and a little bit experience on code.
so I have a localstorage like this:
myDB: "[{"key:"123","label":"abc"}]
I have a div with "abc" as value:
<div id="name">abc</div>
And many id's div clone with different value
<div id="name">abc</div>
<div id="name">cde</div>
<div id="name">efg</div>
I want to read the value of the ID "name", make a if/else like looking "abc" are in the localstorage, if yes delete it with the key. else not delete.
I have thinking of using document.getElement to get value from ID and compare it to localstorage and using if else to do that thing. But there are many clone have that event to trigger the function to delete it. So the function don't know which ID's value to be compare and delete it.
I really awkward for this newbie question. But I have to ask, many thanks first :)
*New question:
I want to delete last element of the localstorage.
Can I convert localstorage to array then using array.pop(). Then convert the changed array again to the localstorage?
First, as was mentioned by others, id must be unique. You can use any other attribute instead, for example, class:
<div class="name">abc</div>
<div class="name">def</div>
<div class="name">ghi</div>
<div class="name">jkl</div>
<div class="other">mno</div>
Then, to query these elements, you could use document.getElementsByClassName("name") which will return you an array-like object. You can convert this object to an array of values using a combination of spread syntax and map method:
let values = [...document.getElementsByClassName("name")].map(e => e.innerHTML);
To work with the local storage you can use localStorage.setItem and localStorage.getItem. As you know, the local storage stores only strings, so JSON.parse and JSON.stringify methods will be helpful too.
Here is the example of code:
localStorage.setItem("myDB", '[{"key":"123","label":"abc"}, {"key":"456","label":"mno"}]');
console.log('Local storage before: ', localStorage.getItem("myDB"));
// extracting div values to an array
let values = [...document.getElementsByClassName("name")].map(e => e.innerHTML);
// creating a js object from myDB string
let db = JSON.parse(localStorage.getItem("myDB"));
// leaving only those elements, which labels are not in the values array
localStorage.setItem("myDB", JSON.stringify(db.filter(item => !values.includes(item.label))));
console.log('Local storage after: ', localStorage.getItem("myDB"));
JSFiddle link: https://jsfiddle.net/v03wpgq1/4/
id attributes should be unique on the page, otherwise only the last one on the page has the ability to be referenced easily (or at least, properly).
There should be a section that contains these which makes them easily queryable. Perhaps inside of an element with an id guaranteed to uniquely hold a set of name value pairs.
Using document.querySelectorAll is your best bet for finding these elements, and will be made easier by creating a structure that can be queried.
With a set of items to look for, it should be easy to iterate and test for values and keys inside of localStorage.

Changing object data in javascript of a Django/Heroku website

I'm wondering if it's possible for me to change the values of a data object inside my javascript. The javascript receives postmessages from an iframe and I need to be able to store that information to the correct objects, but I'm not quite sure how to do it on the HTML surface or if it's possible to do in the javascript surface.
I can call
{{ game.high_score}}
in the HTML to fetch the high_score of a certain game object, but my attempts at working out how to have my javascript send values to these objects flies right over my head.
The most recent venture I tried was simply doing
game.gameData.name = somevalue;
in the javascript, but this doesn't seem to change the global value for this data object value (the change is not seen outside of the javascript).
Are there any solid ways of handling this inside/outside of javascript in Django/Heroku environment?
Edit:
I'm not having trouble at grabbing data from POST: The question might as well be as to how I can change a game object's value when the value I want to change it to stems from javascript.
The game class object I have looks something like this:
class GameInstanceDto:
def __init__(self, base: GameIdentityDto, high_score: int, state: str):
self.base = base,
self.high_score = high_score,
self.state = state
if I can call the game specific highscore in the HTML with
{{ game.high_score }}
and I want to alter the value of it in javascript, I personally tried to go with
game.high_score = "2500";
just to see if the value of the high_score would change, but I didn't see it change at all.
I'm not sure if you want to POST the changes back to your model or not so let's take it 1 step at a time.
Alter {{ game.high_score }} with JavaScript
<div id="high_score">{{ game.high_score }}</div>
<script>
var high_score = document.getElementByID('high_score');
high_score.innerHTML = 2500;
</script>
Now, it you actually want to send in back as a POST, make element high_score an input field within a form

Where to store initial Object's values for the Objects that can be changed, in AngularJS?

I'm using a factory to create different user-Objects from data which comes from the Server. Each user-Object has a "userGroup"-property. A list of users is displayed using ng-repeat in the View. And there it is possible to change the userGroup-value from "basic" to "admin", because of the AngularJS 1 two way binding. So the original values of the Object are gone. So my question is: when we want to cancel the made changes where should the initial value {userGroup: "basic"} be stored?
I was thinking about two possible solutions:
create an additional property "initUserGroup" in the User Factory Class and store a value for each Object
use localstorage (up to 20 records must be saved at once)
Are there any best practices for such cases?
For example, you can backup whole object in a property like _backup (using angular.copy) and restore if you with to undo changes (using angular.extend). Here is an example:
$scope.editItem(item) {
item._backup = angular.copy(item);
}
$scope.undoEdit(item) {
angular.extend(item, item._backup);
//delete unused data
delete(item._backup);
}
In this case you won't need to save data outside current object.

How to read / get values from node's field using JavaScript in Drupal?

Let's say I have three field machine names in Drupal on a content type in Drupal:
company_color_schema , company_logo , and company_some_picture
I would like to retrieve the company_color_schema which will give me a plain text hex color code using JavaScript so that I can use it for a div background color.
Is there a way to access these values using JavaScript? I've looked at available documentation, but none seems to cover it.
You should use drupalSettings for this.
You can attach them in hook_node_view or similar depending on your needs
Actually, you don't need javascript to set div background. The better way is to use hook_preprocess_HOOK:
mymodule_preprocess_node(&$vars) {
$vars['background'] = $vars['node'][WHATEVER_VALUE];
}
Put this code into your module, clear caches and then you can use $background variable in your node.tpl.php
One way you can do this is to place JavaScript code in a view template file, at least part of it. So let's say you have a JavaScript row like this:
<?php $value_you_get_from_php = ... ; ?>
<script>
var bcgColor = <?php echo $value_you_get_from_php; ?>;
</script>
So you'll get your color field value from PHP and print it out inside inline JavaScript code, exactly at position where you defined your JavaScript variable value. Then you can use that JavaScript variable anywhere you need it.
Another way would be making an Ajax call with i.e. the node id as parameter, but the first option is easier, if it's acceptable.
Or, the easiest solution (inspired by Artreaktor's answer): Just shoot color directly from a template file - add the style tag attribute and set color from that. Artreaktor's solution may be more by rules, but mine is easier to implement.
Oh, yes. In drupal 8:
Create a view, build it's query to show your fields
Go to Admin/extend and enable "RESTful Web Services" module
Add REST export display to it
Create path for your REST export display
select format "serializer" with settings:
Force using fields - checked;
json - checked;
You're pretty done. Ajax the url in your script, parse the JSON and you have your fields in JS.

How do I separate data models and local-data models in Angular?

I hope I can expain myself what I mean.
Let's say I have a car resource. The car has the attributes color, name or whatever.
I get the list of cars using a service, something like cars.index().
But in the interface I have all the cars and when I click on one car, a little popup appears showing the inputs to edit the color and the name.
And here comes the issue. Where do I save the displayingInputs attribute?
Should I save it directly in the car resource and then just send the original attributes when submitting to the updated resource?
Should I create a new service called carWidget or something along the lines that each one has something like:
{
car: cars.get(carId),
displayingInputs: false
}
Should I store the displayingInputs inside a carWidget directive scope? What happens if I need to change the `displayingInputs from the parent scope? (for example when making a "display all"/"hide all" button)
Something else?
My best bet is #3, but I'm not sure how should I access the displayingInputs from outside the widget.
If you want to keep your car model clean, you can have a separate variable editedCar and display each popup with ng-show="car == editedCar".
If multiple cars can be edited at the same time, editedCars can be an associative array (car ID => boolean) and display popups using ng-show="editedCars[car.id]".
Another way not to send certain car properties is to prefix their name with a $ sign. This was simply use car.$displayingInputs. Be careful for name collisions as Angular uses this prefix to store internal data.
From the angular.toJson doc:
Serializes input into a JSON-formatted string. Properties with leading
$ characters will be stripped since angular uses this notation
internally.

Categories