The directional effect of a magnetic field on the onset of oscillatory convection is studied numerically in a confined three-dimensional cavity of relative dimensions 4:2:1 ͑length:width:height͒ filled with mercury and subject to a horizontal temperature gradient. The magnetic field suppresses the oscillations most effectively when it is applied in the vertical direction, and is the least efficient when applied in the longitudinal direction ͑parallel to the temperature gradient͒. In all cases, however, exponential growths of the critical Grashof number, Gr c ͑Gr, ratio of buoyancy to viscous dissipation forces͒ with the Hartmann number ͑Ha, ratio of magnetic to viscous dissipation forces͒ are obtained. Insight into the damping mechanism is gained from the fluctuating kinetic energy budget associated with the time-periodic disturbances at threshold. The kinetic energy produced by the vertical shear of the longitudinal basic flow dominates the oscillatory transition, and when a magnetic field is applied, it increases in order to balance the stabilizing magnetic energy. Moreover, subtle changes in the spatial distribution of this shear energy are at the origin of the exponential growth of Gr c . The destabilizing effect of the velocity fluctuations strongly decreases when Ha is increased ͑due to the decay of the velocity fluctuations in the bulk accompanied by the appearance of steep gradients localized in the Hartmann layers͒, so that an increase of the shear of the basic flow at Gr c is required in order to sustain the instability. This yields an increase in Gr c , which is reinforced by the fact that the shear of the basic flow naturally decreases at constant Gr with the increase of Ha, particularly when the magnetic field is applied in the vertical direction. For transverse and longitudinal fields, the decay of the velocity fluctuations is combined with an increase of the shear energy term due to a sustained growth in stabilizing magnetic energy with Ha.