Vue add class to element without v-model:class? - javascript

I have two elements, that are in two completely different parts of the DOM. And I'm trying to connect the two, so when you hover one element, the other one shows an effect.
The first element is in a component and is being displayed with code like this inside a component:
<button #mouseover="$emit( 'event-hovered', event.id )" #mouseout="$emit( 'event-not-hovered' )">
Button text
</button>
The second element is being generated using code from an AmCharts-demo:
createCustomMarker: function (image) {
var element = document.createElement('button');
element.className = 'map-marker the-id-' + image.id;
element.title = image.title;
element.style.position = 'absolute';
element.dataset.target = "#id" + image.id;
element.setAttribute('data-toggle', 'modal');
image.chart.chartDiv.appendChild(element);
return element;
}
As can be seen, then I've made a #mouseover that emits the id back to he main instance. In the main instance, then I have a method that finds the second element. But I do that using regular javascript, since I've had issues rewriting that createCustomMarker-function, so both Vue and AmCharts grasps what's going on. But this means that I can't add a class to the second elements (generated by createCustomMarker), the conventional v-model:class-way. I tried doing this in a method in the main instance:
eventHovered: function( elementId ){
let markerWithId = document.getElementById( 'id' + elementId );
markerWithId.classList.add("event-hovered");
console.log( markerWithId );
}
When I console.log the markerWithId, then I can see that that has the added class (event-hovered). But that doesn't appear on the screen, and I assume that's because Vue is controlling the DOM.
So how do I submit the element back to the DOM?
And is this a stupid way of doing this?

Try calling the validateNow() function after you edit the class on the marker.
As seen here:
https://docs.amcharts.com/3/javascriptcharts/AmCoordinateChart
From the Docs:
This method should be called after you changed one or more properties of any class. The chart will redraw after this method is called.Both attributes, validateData and skipEvents are optional (false by default).

Related

how to modify one section from another

I am trying to figure out how to modify some properties of a section (such as text color or visibility) when clicking one element of a grid that has multiple colors (see image_1). I have already done the function to get the color of the clicked element but now I want to send this color value to the other section of the page (which has its own id).
when i use getElementById() function it returns null and i do not know how to solve it...
IMAGE_1
function getColor(cell) {
var actual = document.getElementById(cell.id);
color = actual.style.background;
idWrap = actual.id.substr(0,3);
alert("#"+idWrap);
var element = document.getElementById("#"+idWrap)
element.style.backgroundColor = 'red';
}
The problem is that you are passing the # to the document.getElementById(...) function. Simply remove it and it should work:
var element = document.getElementById(idWrap)

Create html elements inside tooltip for a chrome extension

I want to create an HTML element (a div) using javascript to use that as a tooltip.
I can create the simple element by doing:
const element = document.createElement("div");
element.id = "myID"
and that works fine...however, I want to add a table (and some other HTML) inside the tooltip, so I was trying to do
element.appendChild(childElement); //where the childElement is another document.createElement("") that contains all the HTML I want.
or:
element.insertAdjacentHTML('afterbegin', '<table></table>');
however, nothing happens. there's no error, but it won't append it either. Am I missing something?
If it matters, this is happening inside the contentScripts.js of a chrome extension I'm building.
EDIT
Full code of div creation:
const element = document.createElement("div");
element.id = "tooltip-creation";
element.classList.add("tooltip");
const childElement = document.createElement("div");
childElement.id = "data";
//I've attempted to do .appendChild, innerHTML, and .insertAdjacentHTML (as can be seen here) and neither works but no error is given.
element.appendChild(childElement);
element.insertAdjacentHTML('afterbegin','<table border="1"><tr><td><strong>OMG</strong></td></tr></table>');
element.innerHTML = "<table border="1"><tr><td><strong>OMG</strong></td></tr></table>";
Separately I have 2 functions that do:
document.addEventListener("mouseover", function(e){
if (e.target.classList.contains("tooltip")) {
createTooltip(e);
}
});
document.addEventListener("mouseout", function(e){
if (e.target.classList.contains("tooltip")) {
removeAllTooltips();
}
});
I think your issue is that you're not actually appending the tooltip to anything. You need to append your element to a node that is already in the DOM. Here is a working example (without any CSS) that I got from your code, the only difference being that I appended the element node to an existing element in the DOM called root.
https://jsfiddle.net/irantwomiles/09o7vuj5/12/

How to remove two custom buttons from the controlBar component

I've added two custom buttons (for custom chapter navigation) and later in my code I want to delete/hide them. But using the removeChild() only remove one of the two (even by doing it twice)
Adding them work great but it's really the removing where I'm getting in troubles.
This is what I've tried but I can't delete both
var nextChapButton = myPlayer.controlBar.addChild("button",{}, 1);
var nextChapButtonDom = nextChapButton.el();
nextChapButtonDom.innerHTML = ">>";
var prevChapButton = myPlayer.controlBar.addChild("button",{}, 0);
var prevChapButtonDom = prevChapButton.el();
prevChapButtonDom.innerHTML = "<<";
myPlayer.controlBar.removeChild("Button");
//even doing it twice the ">>" button remains
myPlayer.controlBar.removeChild("Button");
And I cant declare "button" and "button2" to differenciate them or I get the following error because it's not videojs a component
Uncaught Error: Component Button2 does not exist
at ControlBar.addChild (video.js:3525)
at loadVideo (load.js:261)
at loadPage (load.js:196)
at startConfig (load.js:171)
at HTMLButtonElement.onclick (load.html:114)
You already had everything you needed to remove the buttons: prevChapButtonDom and nextChapButtonDom. Removing the buttons would be:
nextChapButtonDom.remove();
prevChapButtonDom.remove();
I created a Codepen to show removing the elements via button. Please note I used jQuery for simplicity but it's not in any way required to remove the button elements.

Angular 2 - Dynamically create/inject component into specific element inside *ngFor loop

I am looping through a list of metrics and inside each loop there is a button that would be clicked to render a graph at a specific div within the HTML of the loop. The graph is a separate component, however I cannot seem to figure out how to target the correct HTML element to load the graph component into. I started by creating a component rendering function and call it like this:
loadMetricGraph(metric) {
let selector = "[id=metricGraph-" + metric.id + "]";
this.renderComponent(LineGraphHorizontalComponent, selector, metric.data);
}
renderComponent(componentClass, selector, data) {
return this.compiler
.compileComponentAsync(componentClass)
.then((factory:ComponentFactory<any>) => {
let cmpRef:ComponentRef<any> =
factory.create(this.injector, null, selector);
cmpRef.instance.inputData = data;
(<any>this.appRef)._loadComponent(cmpRef);
return cmpRef;
});
}
In the loop I have a div that would be the target for the loaded component, however I am stuck on how to pass the correct selector to the renderComponent() function. I have attempted to use
id="graphData-{{ metric.id }}" And then a selector of "[id=graphData-" + metric.id + "]". I know this is not the correct way to do this, but I am not sure how to proceed.
You can't dynamically add HTML and get components or directives created for this HTML. If you want to dynamically add components then you need to use ViewContainerRef.createComonent.
See Angular 2 dynamic tabs with user-click chosen components shows how to do this declaratively using a helper component.

Can't understand Javascript eventhandler with for loop code

I'm trying to learn JavaScript and I saw a code to change the css style of a web page depending on the button you press.
I can't understand why or how a for loop indicate witch button was press. Here is the javascript part:
var buttons = document.getElementsByTagName("button");
var len = buttons.length;
for (i = 0; i < len; i++) {
buttons[i].onclick = function() {
var className = this.innerHTML.toLowerCase();
document.body.className = className;
};
}
http://jsfiddle.net/qp9jwwq6/
I looked on the net and w3 school but they don't explain that code with a for loop. Can someone explain it to me?
Thank you
Lets break it down.
First we need to have access to the DOM element on the page, so we do that by using a method on the document itself which will return the element we want to manipulate.
var buttons = document.getElementsByTagName("button");
The buttons var will be a list of ALL the buttons on the page. We want to do something with all of them, so first we cache the length of the list, i.e, count how many buttons we have.
var len = buttons.length;
Then we basically say: set i to 0, and step it up one until its equal to the number of buttons we have.
for (i = 0; i < len; i++) {
Now, to access one button from the list, we need to use the brackets notation. So buttons[0] is the first element, buttons[1] is the second, etc. Since i starts at 0, we put i in the brackets so that on each iteration it will access the next button in the list.
buttons[i].onclick = function() {
var className = this.innerHTML.toLowerCase();
document.body.className = className;
};
}
This is equivalent of doing:
buttons[0].onclick = function() {
var className = this.innerHTML.toLowerCase();
document.body.className = className;
};
buttons[1].onclick = function() {
var className = this.innerHTML.toLowerCase();
document.body.className = className;
};
buttons[2].onclick = function() {
var className = this.innerHTML.toLowerCase();
document.body.className = className;
};
// etc.
But of course that is super inefficient, and we may not know how many buttons the page has. So we get all the buttons there, find out how many there are, then go through each button and assign an event handler to it along with a new class.
Now, looking at the onclick handler itself we can see that it first finds the HTML within the button being clicked, turns it into lowercase letters, and assigns it to a variable:
var className = this.innerHTML.toLowerCase();
By using this we're ensuring that each button will know to get it's own innerHTML when clicked. We're not tracking which button is which, we're just telling each button to check it's own content.
Then what it does is change the class of the body HTML element to whatever it is that we just parsed
document.body.className = className;
So say you have something like
<button>success</button>
<button>failure</button>
<button>warning</button>
Clicking the first button would set the <body> element's class to success, clicking the second would set it to failure, and the third would set it to warning.
First line saves all buttons in a variable called buttons. This is actually an array since there can be several buttons on the page. Then you iterate through each button and define a function which should be executed onclick. Lets say you have 2 buttons then it will be buttons[0] and buttons[1] which get the function.
Firstly, speaking generally, the underlying basis for this code is a little wonky and unusual and non-robust, so don't anticipate that you're on the brink of learning any powerful insight into JavaScript or code design.
On to the answer:
The for-loop does not "indicate" which button was pressed. Rather, it loops through every button element on the page and assigns the exact same function definition to the onclick attribute of each element. The code that ends up running when a particular button element is clicked (here I'm talking about the function body) assigns a CSS class to the body element by assigning to document.body.className.
Your question is asking how the function knows which class name to assign to document.body.className. The function grabs the class name from the innerHTML of the button element, which is accessible as this.innerHTML (because in an event handler, this is a reference to the element on which the triggering event occurred). The HTML <button> element is a little bit special, in that, although it is generally a simple-looking button, it is also a non-leaf node, meaning it contains its own HTML. You can put a lot of things in there, but in this example, they just have a plain text node which consists of exactly (or nearly exactly) the class name (Normal for one and Changed for the other). That's how the function can get a CSS class name that is specific to that button; it grabs it from the text inside the clicked <button> element.
I said "nearly exactly" back there because there's actually a letter-case difference between the button text and the actual CSS classes they've defined in the CSS rules (which are normal and changed). That's why they have to lower the letter-case of the extracted button text (toLowerCase()) before assigning the class name. CSS classes are case-sensitive (see Are CSS selectors case-sensitive?).
As I said, this is unusual code. It is rather inadvisable to create a mapping (especially an inexact mapping!) between plain HTML text and code metadata (CSS classes in this case).

Categories

Resources