How do I deselect/defocus a GUI element by clicking anywhere?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By popcar2

If you’re making a GUI app in Godot, it can be weird that it doesn’t de-select elements by clicking anywhere else in the application. In websites and native apps for example, you can click anywhere to de-select a text box that’s currently highlighted. Godot doesn’t let go of focus unless you specifically click on another Control node to take focus from you.

Luckily I found an answer after a few hours of searching.

:bust_in_silhouette: Reply From: popcar2

This answer was mostly from

Basically, this script detects if you left click anywhere outside the boundaries of this control node, and releases focus when triggered. You can add this script to any Control node.

func _input(event: InputEvent):
	if event is InputEventMouseButton and event.is_pressed() and event.button_index == 1:
		var evLocal = make_input_local(event)
		if !Rect2(Vector2(0,0), size).has_point(evLocal.position):