Hi,
I have a mega menu that when the main menu items is hovered over the mega menu the div is displayed. I want to keep the div from being shown off the right of the browser screen. I have the following that determines the amount a div is off the right of the browser:
function keepMenuLeft(){
var div_width = $("li.hovering div").width();
var screen_width = $(window).width();
var offset = $("li.hovering div").offset();
var left = 0;
if (offset.left + div_width > screen_width) {
left = (offset.left + div_width) - screen_width;
}
}
The variable left equals the amount left the div needs to be moved to be completely displayed in the current window.
The issue I am not sure how to deal with is how to apply this calculation to the div? I can’t use addClass() as the left value will change based on the differences in the currently selected mega menu div. However in-line styles are a bad idea and not great for accessibility.
How would you recommend that would be the best way to add the dynamically calculated left value offset to the div?
Regards,
Steve
Well I got this working with inline styles, like this:
$(document).ready(function() {
function addMega(){
$(this).addClass("hovering");
keepMenuLeft();
}
function removeMega(){
$(this).removeClass("hovering");
removeKeepMenuLeft();
}
var megaShowConfig = {
interval: 300,
sensitivity: 4,
over: addMega,
timeout: 500,
out: removeMega
};
function removeKeepMenuLeft(){
//clear inline styles for next hover new position
$('.mega_menu').each(function(idx,el){
el.style.left='';
});
$('.mega_menu').each(function(idx,el){
el.style.position='';
});
}
function keepMenuLeft(){
var div_width = $("li.hovering div").width();
var screen_width = $(window).width();
var offset = $("li.hovering div").offset();
var left = 0;
if (offset.left + div_width > screen_width) {
left = (offset.left + div_width) - screen_width;
left = 0 -left - 30; //extra 30 (px) account for padding and margins
left = left + "px";
$("li.hovering div.mega_menu").css('left',left);
$("li.hovering div.mega_menu").css('position','relative');
}
}
$("li.mega").hoverIntent(megaShowConfig)
});
The section of html that this operate on is
<div class='mega_menu curved'>
<div class='left_sub_col'>
<h3><a href="#events_overview">Events Overview</a></h3>
<p class='shout'>Keeping our Auto community engaged and giving back!</p>
<ul>
<li><a href='#technical_courses'>Golf - Wallys</a></li>
<li><a href='#additional_courses'>ABM</a></li>
<li><a href='#full_day_workshops'>Women's Car Care Awareness</a></li>
<li><a href='#odp_card_training'>Member Events</a></li>
</ul>
</div>
</div>
As I mentioned, I don’t like to use inline styles but this is the only way I could see getting this to work. If you have any other (better) way I (and probably others) would appreciate knowing 
Regards,
Steve