Pratirup Mukherjee Pratirup Mukherjee - 11 days ago 5
Javascript Question

How to add css code in onmouseover="hover('')" [JS]

I can't adjust my text to be center aligned. I tried to put css code in

onmouseover="hover('')"
but it doesn't work. What is the get around for this?

Middle circle with id="content" that changes the tag on hover

<div id="circle">
<p id="content">
<b><span>Services</span></b>
</p>
</div>


JS Code that I included in the html tag to change content on hover

<a href="">
<div onmouseover="hover('<b>BPO</b>')" onmouseout="hover('<b>Services</b>')" class="scaling" id="circle-2">
<img src="/static/img/2.png" onmouseover="this.src='/static/img/2b.png'" onmouseout="this.src='/static/img/2.png'" style="margin-top:5px;" width=100px/>
</div>
</a>
<a href="">
<div onmouseover="hover('<b>Web Development</b>')" onmouseout="hover('<b>Services</b>')" class="scaling" id="circle-3">
<img src="/static/img/4.png" onmouseover="this.src='/static/img/4b.png'" onmouseout="this.src='/static/img/4.png'" style="margin-top:5px;" width=100px/>
</div>
</a>


JS Code that changes the content of the
<p>
tag

function hover(description) {
console.log(description);
document.getElementById('content').innerHTML = description;
}


everything is working properly but I can't adjust the text to be in the center regard less of the
<p>
tag length .
The main question is how do i add css code in
onmouseover="hover('')"


What i want it to look like

what it looks like

Answer

Typically, if you want some element to listen to "mouseover" event, the best way to go is to use EventTarget#addEventListener. Just like this:

const node = document.getElementById('hover');

node.addEventListener('mouseover', () => {
    node.innerText = `Last time mouseover'd at ${new Date()}.`;
});

So, now, you need to update children of #content and src attribute of an image under mouse cursor.

The HTML would look like this:

<p id="content">
  Services
</p>

<a href="">
  <div class="scaling" id="circle-2">
    <img src="/static/img/2.png" />
  </div>
</a>
<a href="">
  <div class="scaling" id="circle-3">
    <img src="/static/img/2.png" />
  </div>
</a>

while JS code would look like this:

const content = document.getElementById('content');
const circle2 = document.getElementById('circle-2');
const circle3 = document.getElementById('circle-3');

circle2.addEventListener('mouseover', () => {
  circle2.children[0].src = '/static/img/2b.png';
  content.innerText = 'BPO';
});

circle2.addEventListener('mouseout', () => {
  circle2.children[0].src = '/static/img/2.png';
  content.innerText = 'Services';
});

circle3.addEventListener('mouseover', () => {
  circle3.children[0].src = '/static/img/4b.png'
  content.innerText = 'Web Development';
});

circle3.addEventListener('mouseout', () => {
  circle3.children[0].src = '/static/img/4.png'
  content.innerText = 'Services';
});

(check out this fiddle).