Tutorial :Trigger Div Click From Link


I have a site http://www.thebalancedbody.ca/ and there is a pop out contact form on the left (Contact) which has this id <div id="mycontactform">.

There is also a link in the footer called CONTACT US

<a href="#"  title="CONTACT US">CONTACT US</a>  

and I need this link to trigger the pop out contact form as if the contact tab was clicked manually.

Is this possible and how would I do it?




All of the suggested solutions should be working. But I think that you need to prevent the anchor's default action.

Add this code within a <script> tag in the <head> section of your document.

$(document).ready(function(){      $("#contact").click(function(event){          event.preventDefault(); //stops the browser from following the link          $("#contactable").click(); //opens contact form          alert("Showing mycontactform"); //remove this when it's working      });  });  

You will need to add an 'id' tag to your contact anchor:

<a href="#" id="contact" title="Contact Us">CONTACT US</a>  

You will also need to make sure you include jQuery in the <head> section of your document.

Add this line after the <head> tag:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>  


Try this:

$(function(){      $("#contact").click(function () {        $("#contactable").trigger('click');      });  });    <a title="CONTACT US" href="#" id="contact">CONTACT US</a>  


$(function() {            $('#foo').bind('click', function() {                alert($(this).text());            });            // I used mouseover just because and           // for no reason. could be anything          $('#bar').mouseover(function() {                $('#foo').trigger('click');            });      });  


<a href="#" id="foo">foo</a>  <a href="#" id="bar">boo</a>  


Use $("#divId").click();. This would fire the click event in the div with the specified ID.

The code given below is tested to work on Chrome and IE8.

<html>      <head>          <title>Test</title>          <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>          <script type="text/javascript">              $(function() {                  $("#myDiv").click(function() {                      alert('Clicked!');                  });                    $("#myLink").click(function() {                      $("#myDiv").click();                  });              });          </script>      </head>      <body>          <div id="myDiv">Some Text</div>          <a id="myLink" href="#">Link</a>      </body>  </html>  


I have to admit defeat on this one. I don't believe there is a solution based on the above answers (although I know they work in test environments), they just don't work in my exact case.

The reason for this is that if you do a view source on http://www.thebalancedbody.ca/ the DIV #contactable

Is not exposed in the source so no matter what I do these approaches won't work. The associated javascript for the pop out form is here, maybe that will give some clues?

/*   * contactable 1.2.1 - jQuery Ajax contact form   *   * Copyright (c) 2009 Philip Beel (http://www.theodin.co.uk/)   * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)    * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.   *   * Revision: $Id: jquery.contactable.js 2010-01-18 $   *   */    //extend the plugin  (function($){        //define the new for the plugin ans how to call it        $.fn.contactable = function(options) {          //set default options            var defaults = {              name: 'Name',              email: 'Email',              message : 'Message',              subject : 'A contactable message',              label_name: 'Name',        label_email: 'E-Mail',        label_website: 'Website',        label_feedback: 'Your Feedback',        label_send: 'SEND',              recievedMsg : 'Thankyou for your message',              notRecievedMsg : 'Sorry but your message could not be sent, try again later',              disclaimer: 'Please feel free to get in touch, we value your feedback',              hide_email: 'false',        hide_website: 'false',              fileMail: 'mail.php',              hideOnSubmit: true          };            //call in the default otions          var options = $.extend(defaults, options);          //act upon the element that is passed into the design              return this.each(function(options) {              //construct the form              div_form = '<div id="contactable"></div><form id="contactForm" method="" action=""><div id="loading"></div><div id="callback"></div><div class="holder">';              div_form += '<p><label for="name">'+defaults.label_name+' <span class="red"> * </span></label><br /><input id="name_mc" class="contact" name="name" /></p>';              if(defaults.hide_email == 'false'){                div_form += '<p><label for="email">'+defaults.label_email+' <span class="red"> * </span></label><br /><input id="email_mc" class="contact" name="email" /></p>';            }            if(defaults.hide_website == 'false'){                div_form += '<p><label for="email">'+defaults.label_website+' <span class="red"> * </span></label><br /><input id="website_mc" class="contact" name="url" /></p>';            }              div_form += '<p><label for="comment">'+defaults.label_feedback+' <span class="red"> * </span></label><br /><textarea id="comment_mc" name="comment" class="comment" rows="4" cols="30" ></textarea></p>';              div_form += '<p><input class="submit" type="submit" value="'+defaults.label_send+'"/></p>';              div_form += '<p class="disclaimer">'+defaults.disclaimer+'</p></div></form>';                $(this).html(div_form);              //show / hide function              $('div#contactable').toggle(function() {                  $('#overlay').css({display: 'block'});                  $(this).animate({"marginLeft": "-=5px"}, "fast");                   $('#contactForm').animate({"marginLeft": "-=0px"}, "fast");                  $(this).animate({"marginLeft": "+=387px"}, "slow");                   $('#contactForm').animate({"marginLeft": "+=390px"}, "slow");               },               function() {                  $('#contactForm').animate({"marginLeft": "-=390px"}, "slow");                  $(this).animate({"marginLeft": "-=387px"}, "slow").animate({"marginLeft": "+=5px"}, "fast");                   $('#overlay').css({display: 'none'});              });                //validate the form               $("#contactForm").validate({                  //set the rules for the fild names                  rules: {                      name: {                          required: true,                          minlength: 2                      },                      email: {                          required: true,                          email: true                      },                      url: {                          required: true,                          url: true                      },                      comment: {                          required: true                      }                  },                  //set messages to appear inline                      messages: {                          name: "",                          email: "",                          url: "",                          comment: ""                      },                              submitHandler: function() {                      $('.holder').hide();                      $('#loading').show();                      name_val = $('#contactForm #name_mc').val();                      if(defaults.hide_email == 'false') email_val = $('#contactForm #email_mc').val();                      else email_val = 'nothing';                      if(defaults.hide_website == 'false') website_val = $('#contactForm #website_mc').val();                      else website_val = 'nothing';                      comment_val = $('#contactForm #comment_mc').val();                      $.post(defaults.fileMail,{subject:defaults.subject, name: name_val, email: email_val, website: website_val, comment:comment_val},                      function(data){                          $('#loading').css({display:'none'});                           if( data == 'success') {                              $('#callback').show().append(defaults.recievedMsg);                              if(defaults.hideOnSubmit == true) {                                  //hide the tab after successful submition if requested                                  $('#contactForm').animate({dummy:1}, 2000).animate({"marginLeft": "-=450px"}, "slow");                                  $('div#contactable').animate({dummy:1}, 2000).animate({"marginLeft": "-=447px"}, "slow").animate({"marginLeft": "+=5px"}, "fast");                                   $('#overlay').css({display: 'none'});                                 }                          } else {                              $('#callback').show().append(defaults.notRecievedMsg);                          }                      });                       }              });          });      };  })(jQuery);  

The other file that maybe useful is this:-

<?php  /*  Plugin Name: Magic Contact  Plugin URI: http://blog.hunk.com.mx/magic-contact/  Description: is a simple and Elegant contact form for Wordpress, taking as it bases to <a href="http://theodin.co.uk/blog/ajax/contactable-jquery-plugin.html">Contactable</a> (jQuery Plugin) By <a href="http://theodin.co.uk/">Philip Beel</a>, After enabling this plugin visit <a href="options-general.php?page=magic-contact.php">the options page</a> to configure settings of sending mail.  Version: 0.1  Author: Hunk  Author URI: http://hunk.com.mx    Copyright 2010  Edgar G (email : ing.edgar@gmail.com)    This program is free software; you can redistribute it and/or modify  it under the terms of the GNU General Public License as published by  the Free Software Foundation; either version 2 of the License, or  (at your option) any later version.    This program is distributed in the hope that it will be useful,  but WITHOUT ANY WARRANTY; without even the implied warranty of  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  GNU General Public License for more details.    You should have received a copy of the GNU General Public License  along with this program; if not, write to the Free Software  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA  */    register_activation_hook( dirname(__FILE__) . '/main.php', 'magic_contact_activate' );    function magic_contact_activate(){    if(!get_option('init_contact')){      update_option( 'recipient_contact', get_bloginfo('admin_email') );      update_option( 'subject_contact', 'A contactable message' );        update_option( 'label_name_contact', 'Name' );      update_option( 'label_email_contact', 'E-Mail' );      update_option( 'label_website_contact', 'Website' );      update_option( 'label_feedback_contact', 'Your Message' );      update_option( 'label_send_contact', 'SEND' );      update_option( 'recievedMsg_contact', 'Thank you for your message' );      update_option( 'notRecievedMsg_contact', 'Sorry, your message could not be sent, try again later' );      update_option( 'disclaimer_contact', 'Please feel free to get in touch, we value your feedback' );        update_option( 'hide_email_contact', 'false' );      update_option( 'hide_website_contact', 'false' );        update_option( 'init_contact', 1 );   }  }    // Add action links  add_action('plugin_action_links_' . plugin_basename(__FILE__), 'AddPluginActions');    function AddPluginActions($links) {     $new_links = array();       $new_links[] = '<a href="options-general.php?page=magic-contact.php">' . __('Settings') . '</a>';       return array_merge($new_links, $links);   }    add_action('admin_menu', 'mc_admin_actions');    function mc_admin_actions(){    add_options_page("Magic Contact", "Magic Contact", 'manage_options',"magic-contact.php", "magic_contact_menu");  }    function magic_contact_menu(){       if ( isset($_POST['submit']) ) {      if ( function_exists('current_user_can') && !current_user_can('manage_options') )        die(__('Cheatin&#8217; uh?'));        update_option( 'recipient_contact', $_POST['recipient_contact'] );      update_option( 'subject_contact', $_POST['subject_contact'] );        update_option( 'label_name_contact', $_POST['label_name_contact'] );      update_option( 'label_email_contact', $_POST['label_email_contact'] );      update_option( 'label_website_contact', $_POST['label_website_contact'] );      update_option( 'label_feedback_contact', $_POST['label_feedback_contact'] );      update_option( 'label_send_contact', $_POST['label_send_contact'] );      update_option( 'recievedMsg_contact', $_POST['recievedMsg_contact'] );      update_option( 'notRecievedMsg_contact', $_POST['notRecievedMsg_contact'] );      update_option( 'disclaimer_contact', $_POST['disclaimer_contact'] );        if ( isset( $_POST['hide_email_contact'] ) ) update_option( 'hide_email_contact', 'true' ); else update_option( 'hide_email_contact', 'false' );          if ( isset( $_POST['hide_website_contact'] ) ) update_option( 'hide_website_contact', 'true' ); else update_option( 'hide_website_contact', 'false' );      }    include 'form-admin.php';  }    add_action('template_redirect', 'script_magic_contact');    function script_magic_contact(){      $base = WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__),"",plugin_basename(__FILE__));       wp_enqueue_script( 'jquery.contactable', $base . 'contactable/jquery.contactable.js', array('jquery') , 3.1);    wp_enqueue_script( 'jquery.validate', $base . 'contactable/jquery.validate.pack.js', array('jquery') , 3.1);    wp_enqueue_script( 'my_contactable', $base . 'my.contactable.php', array('jquery') , 3.1);    wp_enqueue_style( 'contactable', $base . 'contactable/contactable.css' );    }    add_action('wp_footer','div_magic_contact');    function div_magic_contact(){    echo '<div id="mycontactform"> </div>';  }    ?>  


Edit: It looks like it is working as you want, except for that the page isn't at the top. If that's the case check out jQuery's scrollTop function. Also it looks like the 'contactable' div is not attached to the contact section, which could be a problem. If that is not your problem, please edit the question to describe your current problem as it seems to be the interaction with the plugin rather than triggering a div click. Good luck!

Old answer (no longer applicable as source has changed):

The problem in your situation is that the selector (#contact - gets elements with id equal to 'contact') in this :

$(function(){      $("#contact").click(function () {        $("#contactable").trigger('click');      });  });  

Doesn't match the element you are wanting to add the event to :

<a href="#" title="CONTACT US">CONTACT US</a>  

My suggestion would be to add a class to each element that you'll want to trigger the 'contactable' click like this:

<a href="#" class="contactable" title="CONTACT US">CONTACT US</a>  


<a title="CONTACT US" href="#" id="contact" class="contactable">CONTACT US</a>  

and then change your selector to use that class to assign the click function:

$(function(){      $(".contactable").click(function () {        $("#contactable").trigger('click');      });  });  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »