How to open a WordPress menu child link in new window with jQuery

Following is the example code for how to open a WordPress menu child link in new window with jQuery.

jQuery(document).ready(function() {
	jQuery("#menu-item-108 .sub-menu a").click(function()	{
		window.open(jQuery(this).attr('href'), jQuery(this).text(), "scrollbars=yes");
		return false;
	})
})

where menu-item-108 is the ID of parent menu item whose child links will be opened in new browser window (not in new browser tab). If you wanted to open a menu link in new browser check this post on How to open a wordpress menu link in new window/tab

I have created a small piece of core javascript code for someone not using WordPress as cms and jQuery as javascript library. This should give sufficient insight to someone looking to achieve similar kind of task. This example also demonstrates a method to bind an event to one or multiple elements of document sub nodes or elements. Here in this example in which i am ‘binding’ click event to all children elements (<A> tag here) of a given element (which is a <LI> here)

function bindClickTOAsOfLI(targetObj)	{
  var chl_len = targetObj.children.length;
  for(var i=0;i<chl_len;i++)	{
    if(targetObj.children[i].tagName=="A")	{
      var self = targetObj.children[i];
      self.onclick = function()	{
        var tmp = window.open(self.getAttribute("href"), "MyWindow", "scrollbars=yes");
        return false;
      }
    }
    if(targetObj.children[i].tagName=="UL")	{
      ulObjChildren = targetObj.children[i].children;
      ul_obj_chld_len = ulObjChildren.length;
      for(var j=0;j<ul_obj_chld_len;j++)	{
        if(ulObjChildren[j].tagName=="LI")	{
          bindClickTOAsOfLI(ulObjChildren[j]);
          //this will bind to all children in the tree. This function is also useful for getting all child elements
        }
      }
    }
  }
}
window.onload = function()	{
  var targetObj = document.getElementById("menu-item-108");
  bindClickTOAsOfLI(targetObj);
}

How to find the id of my menu item in WordPress?

Do view source of the page and look for a <UL> tag

having a class ending with “menu-container” phrase in the source. Inside this menu container the first <UL>

 element is the parent in the Untitled List tree and following <LI> elements are ones which you are going to find ID of. Each <LI> element should have an ID as shown in the attached image below:

menu-container-wordpress-child-get-javascript

Leave a Reply

Your email address will not be published. Required fields are marked *