So, I am new here and have a few questions about using the "this" keyword in Javascript. I am new to javascript but have much experience with C++. First question, is the "this" keyword just like using self? Secondly, if it is like self, and I use it in say a mouseover function, would the object using the mouseover function be like/self? Whenever I use this I am getting issues.

To give an overview, I have a box that I am resizing using CSS transitions and javascript. For this to work I have to change the width of many objects. I could go and make a function for each and every object, but that is not efficient. I would like a universal change width statement. But, whenever I use "this" and do the mouseover it just crashes and says "this" is a DOMWindow. I have included my function code because I cannot figure out why it is doing this, unless I am doing it wrong. Any help would be greatly appreciated.

function mouseOut(event)
    this.width = "100px";

function mouseOver(event)
    this.width = "200px";

Recommended Answers

All 4 Replies

Member Avatar

This will refer to the self only but it should be an elements or object, you should pass to your event like below:

<input name="c" type="checkbox"  id="hello" value="10" onclick="toogle(this,'10')"/>

Here this refer to the checkbox clicked. For onMouseout use like below

ex: mouseOut(this); //calling functon
    mouseOut(event) { event.width="100px"}

Thanks for the help. This fixed the issue. I think the issue is mostly with my IDE. It only allows me to set mouseOver(event) as the calling function and not mouseOver(this). Thanks again

The usual way of doing this is to change 'this' element onmouseover= and change it back onmouseout= (letting the browser shift and unshift "nearby" elements as needed).

If that is not enough (that is, if you need to change [not just shift] other elements - possibly a lot of them), you can use CSS.

[Note: the following is easier to do than this description makes it look.]

Assign all elements to be affected to the same class (let's call it 'base') and create a rule (let's call it 'basic') that styles elements using #selectors. You can then create a series of similar #selector-based rules (let's call them 'inA', 'inB', etc.) to match the element id='s that are going to trigger the action.

Each trigger element must have an onmouseover=do(this) and onmouseout=done().

The only code in function done() is to copy 'basic' to 'base'.
The code in function do(elem) uses the calling parameter to identify 'this' element and determine from its id= the appropriate rule ('inC' or whatever) that needs to be copied to 'base'.

Member Avatar

Hi RamRod53,

Pleae Mark as Solved, if it is solved!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.