Top Questions:

  • 5 years-11 months

    How to limit characters for textarea including count in jquery

    • Category : java
    • Location : Chandigarh, India
    • Posted On :
    • Posted by : Vikas

    Here are two scenarios where the keyup event will not get fired: The user drags text into the textarea. The user copy-paste text in the textarea with a right click (contextual menu).

    Use the HTML5 input event instead for a more robust solution:

    // jquery
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    
    // html
    <div class="control">
    	<textarea spellcheck="true" maxlength="200" name="question" id="question" class="input-textarea required-entry" cols="5" rows="8" data-validate="{required:true}" aria-required="true"></textarea>
      <div class="limittext"><span class="charnum">200 Characters left</span></div>
    </div>
    
    <script type="text/javascript">
    jQuery(document).ready(function() {
      // edit area start
      var maxLength = 200;
      var textarea_id = "question";
      // edit area end
    
      var html='<span style="color:red;">'+ maxLength + ' characters allowed, excess characters trimmed</span>';
      jQuery("#"+textarea_id).on('input',function(){
          var length = this.value.length;
          if (length >= maxLength) {
            this.value = this.value.substring(0, maxLength);
            jQuery(this).next(".limittext").html(html);
          } else {
            var count=maxLength-length;
            jQuery(this).next(".limittext").html('<span class="charnum">' +count+' Characters left</span>');
          }
      });
    });
    </script>
  • 5 years-11 months

    Dynamically loading an external JavaScript or CSS file using function

    • Category : php
    • Location : Chandigarh, India
    • Posted On :
    • Posted by : Vikas

    To load a .js or .css file dynamically, in a head section, it means using DOM methods to first create a new "SCRIPT" or "LINK" element, assign it the appropriate attributes, and finally, use element.appendChild() to add the element to the desired location within the document tree. It sounds a lot more fancy than it really is. Lets see how it all comes together

    <script type="text/javascript">
    // function
    function loadheadfile(filename, filetype){
    	if(filetype=="js"){
    		var fileref=document.createElement('script')
    		fileref.setAttribute("type","text/javascript")
    		fileref.setAttribute("src", filename)
    	}
    	else if(filetype=="css") {
    		var fileref=document.createElement("link")
    		fileref.setAttribute("rel", "stylesheet")
    		fileref.setAttribute("type", "text/css")
    		fileref.setAttribute("href", filename)
    	}
    	if(typeof fileref!="undefined")
    		document.getElementsByTagName("head")[0].appendChild(fileref)
    }
    
    
    // call function
    loadheadfile('https://tsuyoshiwada.github.io/sweet-scroll/lib/icomoon/style.css','css');
    </script>
     
  • 5 years-11 months

    How to Add Pagination in Your WordPress Theme or Core Php

    • Category : php
    • Location : Chandigarh, India
    • Posted On :
    • Posted by : Vikas

    WordPress offers built-in functionality for navigating through posts. Theme developers can use simple default wordpress pagination function or other pagination function for better customize.

    // Create table in mysql
    CREATE TABLE `your_table_name` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `title` varchar(200) NOT NULL,
      `addtime` int(20) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    
    // Insert table data
    INSERT INTO `your_table_name` (`id`, `title`, `addtime`) VALUES
    (1, 'test', 1299446702);	// addtime is timestamp
    
    
    
    <?php
    // insert this code where your want to add pagination
    // ----------- code start -----------
    
    $table_name =  "your_table_name"; 	// enter your table name
    $item_per_page=5;					// enter number 
    
    $all = $wpdb->get_row( "SELECT count(*) as total FROM {$table_name} WHERE 1=1", ARRAY_A );
    $page_number = (get_query_var('page')) ? get_query_var('page') : 1;
    $offset = ($page_number - 1) * $item_per_page;
    $data = $wpdb->get_results( "SELECT * FROM {$table_name} WHERE 1=1 ORDER BY id DESC LIMIT $offset,$item_per_page", ARRAY_A );
    $cou=$page_number*$item_per_page;
    ?>
    
    <h2>Results <?=$page_number ?>-<?=($cou>$all['total'])?$all['total']:$cou ?> of <?=$all['total'] ?></h2>
    <ul class="pagination">
    	<?php echo pagination($all['total'], $item_per_page, $page_number, site_url()."/your-page-name/?page=%d"); ?>
    </ul>
    
    
    <?php
    foreach ($data as $one) {
    ?>
    		<?=$one['id'] ?> <br />
    		<?=$one['title'] ?>
    <?php
    }
    ?>
    // ----------- code end -----------
    
    
    // add function.php in wordpress----------- code start ----
    
    function pagination($item_count, $limit, $cur_page, $link)
    {
           $page_count = ceil($item_count/$limit);
           $current_range = array(($cur_page-2 < 1 ? 1 : $cur_page-2), ($cur_page 2 > $page_count ? $page_count : $cur_page 2));
    
           // First and Last pages
           $first_page = $cur_page > 3 ? '<a href="'.sprintf($link, '1').'">1</a>'.($cur_page < 5 ? ', ' : ' ... ') : null;
           $last_page = $cur_page < $page_count-2 ? ($cur_page > $page_count-4 ? ', ' : ' ... ').'<a href="'.sprintf($link, $page_count).'">'.$page_count.'</a>' : null;
    
           // Previous and next page
           $previous_page = $cur_page > 1 ? '<a href="'.sprintf($link, ($cur_page-1)).'">&lt;&lt;</a>  ' : null;
           $next_page = $cur_page < $page_count ? '  <a href="'.sprintf($link, ($cur_page 1)).'">&gt;&gt;</a>' : null;
    
           // Display pages that are in range
           for ($x=$current_range[0];$x <= $current_range[1];   $x)
                   $pages[] = '<a href="'.sprintf($link, $x).'">'.($x == $cur_page ? '<strong>'.$x.'</strong>' : $x).'</a>';
    
           if ($page_count > 1)
                   return '<p class="pagination">'.$previous_page.$first_page.implode('&nbsp;&nbsp;', $pages).$last_page.$next_page.'</p>';
    }
    
    // add function.php in wordpress----------- code end ----
  • 5 years-11 months

    how to use ajax in wordpress page

    • Category : php
    • Location : Chandigarh, India
    • Posted On :
    • Posted by : Vikas

    This article, aimed at plugin developers, describes how to add Ajax to a plugin or page. Before reading this article, you should be familiar with the following

    // function.php in Wordpress -------- Start Code--------
    add_action('wp_head', 'dorcode_ajaxurl');
    function dorcode_ajaxurl() {
       echo '<script type="text/javascript">
               var ajaxurl = "'.admin_url('admin-ajax.php').'";
            </script>';
    }
    
    
    add_action( 'wp_ajax_your_dorcode', 'my_dorcode' );
    add_action( 'wp_ajax_nopriv_your_dorcode', 'my_dorcode' );
    
    function my_dorcode() {
    	$data_id = intval( $_POST['data_id'] );
        echo $data_id;
        wp_die();
    }
    // function.php in Wordpress -------- End Code--------
    
    
    
    // Anywhere in Wordpress -------- Start Code--------
    
    // if you need
    var ajaxurl = "<?php echo admin_url('admin-ajax.php') ?>";
    jQuery(document).ready(function($) {
    	var data = {
    		'action': 'your_dorcode',
    		'data_id': 1525
    	};
    	jQuery.post(ajaxurl, data, function(response) {
    		alert('Got this from the server:' + response);
    	});
    
    });
    // Anywhere in Wordpress -------- End Code--------
  • 3 years-4 months

    Copy text to clipboard

    • Category : jquery
    • Location : Chandigarh
    • Posted On :
    • Posted by : Guley

    you can copy text to clipboard and paste where you want

    <button class="btn btn-success" id="copyButton" onclick="copyToClipboard('testing')">Copy</button>
    
    <script type="text/javascript">
    function copyToClipboard(elementId) {
    
      // Create a "hidden" input
      var aux = document.createElement("input");
    
      // Assign it the value of the specified element
      aux.setAttribute("value", elementId);
    
      // Append it to the body
      document.body.appendChild(aux);
    
      // Highlight its content
      aux.select();
    
      // Copy the highlighted text
      document.execCommand("copy");
    
      // Remove it from the body
      document.body.removeChild(aux);
    
    }
    </script>
  • 3 years-4 months

    Prevent auto rotation while uploading in php

    • Category : php
    • Location : Chandigarh
    • Posted On :
    • Posted by : Guley

    You can prevent auto image rotation problem using this code

    function correctImageOrientation($filename) {
      if (function_exists('exif_read_data')) {
        $exif = exif_read_data($filename);
        if($exif && isset($exif['Orientation'])) {
          $orientation = $exif['Orientation'];
          if($orientation != 1){
            $img = imagecreatefromjpeg($filename);
            $deg = 0;
            switch ($orientation) {
              case 3:
                $deg = 180;
                break;
              case 6:
                $deg = 270;
                break;
              case 8:
                $deg = 90;
                break;
            }
            if ($deg) {
              $img = imagerotate($img, $deg, 0);        
            }
            // then rewrite the rotated image back to the disk as $filename 
            imagejpeg($img, $filename, 95);
          } // if there is some rotation necessary
        } // if have the exif orientation info
      } // if function exists      
    }
    
    $target_dir = "blog/";
    $target_file = $target_dir . basename($blogimg);
    $imge=correctImageOrientation($target_file);
    move_uploaded_file($_FILES["blogimg"]["tmp_name"], $imge); 
    $query=mysql_query("insert into tablename (`image_name`) values ('$target_file')");
    
  • 5 years-11 months

    Get content between two strings, tag and brackets using php

    • Category : php
    • Location : Chandigarh, India
    • Posted On :
    • Posted by : Vikas

    If the strings are different [iframe] and [/iframe], take a look at this. copy his code below:

    <?php
    function get_string_between($string, $start, $end){
        $string = ' ' . $string;
        $ini = strpos($string, $start);
        if ($ini == 0) return '';
        $ini  = strlen($start);
        $len = strpos($string, $end, $ini) - $ini;
        return substr($string, $ini, $len);
    }
    $string='testing [iframe]dorcode.com[/iframe] test';
    $parsed = get_string_between($string, '[iframe]', '[/iframe]');
    echo $parsed; // output: dorcode.com
  • 5 years-11 months

    How to Manipulating or Modify the Browser History in Complex HTML5 and JavaScript Applications

    • Category : java
    • Location : Chandigarh, India
    • Posted On :
    • Posted by : Vikas

    URL — The new history entry's URL is given by this parameter. Note that the browser won't attempt to load this URL after a call to pushState(), but it might attempt to load the URL later, for instance after the user restarts the browser. The new URL does not need to be absolute; if it's relative, it's resolved relative to the current URL. The new URL must be of the same origin as the current URL; otherwise, pushState() will throw an exception. This parameter is optional; if it isn't specified, it's set to the document's current URL.

    // modify history
    window.history.pushState(obj, title, url);
    window.history.pushState("", "", 'www.dorcode.com');  
  • 5 years-11 months

    UI Datepicker be made to disable Saturdays and Sundays with custom date

    • Category : jquery
    • Location : Chandigarh, India
    • Posted On :
    • Posted by : Vikas

    I use a datepicker for choosing an appointment day.I want to exclude Saturdays and Sundays from the available choices. Can this be done? If so, how?

    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <input name="datenew" type="text" id="datepicker">
    <script>
    var unavailableDates = ["21-6-2016","22-6-2016","23-6-2016","24-6-2016"];
    function unavailable(date) {
      var day = date.getDay(), Sunday = 0, Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6;
        dmy = date.getDate()   "-"   (date.getMonth()   1)   "-"   date.getFullYear();
      var closedDays = [[Saturday],[Sunday]];
     for (var i = 0; i < closedDays.length; i  ) {
        if (day == closedDays[i][0]) {
          return [false];
       }
    
     }
        if (jQuery.inArray(dmy, unavailableDates) == -1) {
            return [true, ""];
        } else {
            return [false, "", "Unavailable"];
        }
    }
    jQuery(function() {
      jQuery( "#datepicker" ).datepicker({    
        changeMonth: true,
        changeYear: true,
       dateFormat: 'dd MM yy',   
        autoclose: true,
        minDate:  2,
        firstDay: 1,
        beforeShowDay: unavailable
      });
    
    });
    </script>
  • 5 years-11 months

    How to add the media uploader in wordpress plugin

    • Category : php
    • Location : Chandigarh, India
    • Posted On :
    • Posted by : Vikas

    When i click the first upload field (uploading process are success) after insert into post that corresponding media url is appear in the second field not in first. I am not sure where is the problem any suggestion would be great.

    <?php
    wp_enqueue_script('jquery');
    // This will enqueue the Media Uploader script
    wp_enqueue_media();
    ?>
        <div>
        <label for="image_url">Image</label>
        <input type="text" name="image_url" id="image_url" class="regular-text">
        <input type="button" name="upload-btn" id="upload-btn" class="button-secondary" value="Upload Image">
     </div>
    <script type="text/javascript">
    
    jQuery(document).ready(function($){
        $('#upload-btn').click(function(e) {
            e.preventDefault();
            var image = wp.media({ 
                title: 'Upload Image',
                // mutiple: true if you want to upload multiple files at once
                multiple: false
            }).open()
            .on('select', function(e){
                // This will return the selected image from the Media Uploader, the result is an object
                var uploaded_image = image.state().get('selection').first();
                // We convert uploaded_image to a JSON object to make accessing it easier
                // Output to the console uploaded_image
                console.log(uploaded_image);
                var image_url = uploaded_image.toJSON().url;
                // Let's assign the url value to the input field
                $('#image_url').val(image_url);
            });
        });
    });
    </script>
    
    
    
    // UPLOAD ENGINE
    function load_wp_media_files() {
        wp_enqueue_media();
    }
    add_action( 'admin_enqueue_scripts', 'load_wp_media_files' );