jQuery toggle both content and button


<script src="//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function()
{
$( ".sod" ).click(function() {
  $( ".sods" ).toggle(function() {
  });
    $( ".blo" ).toggle("slow");

});

});
</script>

Display as you type input value in div and input type populate with the same text with jQuery

Some situations need a special way of thinking regarding functionality and automation.

This little script sends the text typed in a form/input type to a div and also to another input type so that you can use in many ways the final result – the POST or GET variable created. Also the fist input type works with its defined name.

You can see a working demo here: DEMO

jQuery add/remove hidden input field to form on click

$('#sms-go').on('click',function(){
$('<input>').attr({
    type: 'hidden',
    name: 'sms-yes',
    value: 'yes'
}).appendTo('#form');
console.log('hidden yes added!');
  });


$('#sms-no').on('click',function(){
$('<input>').attr({
    type: 'hidden',
    name: 'sms-no',
    value: 'no'
}).appendTo('#form');
console.log('hidden no added/yes removed!');
  });

I used this little code with a reservation form… to put it simple… the user that wanted to make a reservation could opt in/out of receiving a confirmation SMS a few hours before the scheduled date/time…

Real time display input value in div with jQuery

I used this simple trick to display the name of a person after he sends the form data via Ajax and I needed a different response(not from Ajax), so, I set the response message to display:none via css and get the name or other informations in real time… when the form is submitted… the div becomes visible and shows the result… like Thank you {Name} for sending us etc. …

$('#name_x').keyup(function () {
  $('#get_name').text($(this).val());
});

<pre class="wp-block-code"><code>&lt;form&gt;
<form<input type="text" name="name" id="name_x" size="44" 
placeholder="Type here to see real time result in div..." style="padding:12px;border-radius:4px;border:1px solid grey" >
<br><br>
<div id="get_name"></div>
</form>

You can see a live demo here.

Send data to PHP via AJAX and get response

This is the simple script that I use every time I build one page sites… I use this code to update, delete, modify, add data to Mysql or other DB’s…

This code also get the class or id of the clicked link and can display a result there or in another div… this script can also be modified to play other important parts in the web app…

Hope it helps.

$('.get-delete').click(function() {
    var get_id = $(this).attr('id');
    $("#" + get_id ).toggle(400);
    $.ajax({
        type: 'POST',
        url: 'delete.php',
        data: { idx: get_id},
        success: function(response) {
            $('#result').html(response);
        }
    });
});

jQuery (Ajax) Contact form with all elements

This is my default CONTACT form built with jQuery and CSS.
The form uses a jQuery call to a PHP script that inserts data into a Mysql DB and sends two emails of confirmation, all this under the hood… meanwhile, there is a CSS only animation that displays a message that the data is been sent to the server and shows a positive message if that data was sent without errors and an error message if there was an error.

$(document).ready(function(){

var request;

$("#contact-form").submit(function(event){

    event.preventDefault();

    if (request) {
        request.abort();
    }
    var $form = $(this);
    var $inputs = $form.find("input, textarea");
    var serializedData = $form.serialize();
    $inputs.prop("disabled", true);
    request = $.ajax({
        url: "contact-form.php",
        type: "post",
        data: serializedData
    });
    request.done(function (response, textStatus, jqXHR){
        //console.log("Hooray, it worked!");
        $(".show-success").slideToggle();
        //$(".hide-contact").slideToggle();
    });

    request.fail(function (jqXHR, textStatus, errorThrown){
        console.error(
            "The following error occurred: "+
            textStatus, errorThrown
        );
        $(".show-error").slideToggle();

    });


    request.always(function () {
        $inputs.prop("disabled", false);
    });

});

});
<style>
.frm{padding:9px;border-radius: 3px;background:#ECEFF1;font-size: .8em; border:0px; width: 100%;font-weight: 300;box-sizing: border-box;}
.frb{background:#3498DB}
.pt-12{padding-top:12px}.small{font-size: .8em}
.hide{display:none}
.org-bg{background:#E74C3C;padding: 12px;border-radius: 3px;margin-bottom: 12px;color: #fff}.grn-bg{background:#52BE80;padding: 12px;border-radius: 3px;margin-bottom: 12px;}
.orange-bg{font-family:'Quicksand',sans-serif;font-weight:400;font-size:.8em;}
.fc{padding-bottom:12px;font-family:'Quicksand',sans-serif;font-weight:400;font-size:1.2em}

#loading{display:none}

.spinner {
  margin: 0px auto 0;
  width: 70px;
  text-align: center;
}

.spinner > div {
  width: 18px;
  height: 18px;
  background-color: #333;

  border-radius: 100%;
  display: inline-block;
  -webkit-animation: sk-bouncedelay 1.4s infinite ease-in-out both;
  animation: sk-bouncedelay 1.4s infinite ease-in-out both;
}

.spinner .bounce1 {
  -webkit-animation-delay: -0.32s;
  animation-delay: -0.32s;
}

.spinner .bounce2 {
  -webkit-animation-delay: -0.16s;
  animation-delay: -0.16s;
}

@-webkit-keyframes sk-bouncedelay {
  0%, 80%, 100% { -webkit-transform: scale(0) }
  40% { -webkit-transform: scale(1.0) }
}

@keyframes sk-bouncedelay {
  0%, 80%, 100% { 
    -webkit-transform: scale(0);
    transform: scale(0);
  } 40% { 
    -webkit-transform: scale(1.0);
    transform: scale(1.0);
  }
}

.trimit{background: rgba(149, 192, 234);padding: 12px; border-radius: 3px;margin-top:12px;font-family:'Quicksand',sans-serif;font-weight:400;font-size:.8em;}
</style>
<!-- form ROW -->
<div class="row pt-12x">

<div id="loading">
	
<div class="spinner">
  <div class="bounce1"></div>
  <div class="bounce2"></div>
  <div class="bounce3"></div>
</div>

<div class="trimit"><i class="far fa-paper-plane fa-fw"></i> Se trimit datele...</div>

</div>

<!-- Error Handlers --><div id="show-success"></div>
<div class="grn-bg orange-bg list-font-1 hide show-success"><i class="fas fa-check-square fa-fw"></i> <b>Vă mulțumim!</b> Am primit mesajul dumneavoastră.</div>
<div class="org-bg orange-bg list-font-1 hide show-error"><i class="far fa-question-circle fa-fw"></i> <b>Eroare!</b> Mesajul nu a fost trimis.</div>
<!-- .Error Handlers -->
<!-- form --> <form id="contact-form">                        
  <div class="hide-contact">
<div class="fc"><i class="fas fa-user fa-fw brown"></i> Formular contact</div>

            <div>
              <input type="text" name="name" class="frm" placeholder="Nume" required="">
            </div>
            <div class="pt-12">
              <input type="text" name="email" class="frm" placeholder="Email@exemplu.com" required="">
            </div>

            <div class="pt-12">
              <input type="text" name="phone" class="frm" placeholder="Număr telefon" required="">
            </div>

            <div class="pt-12">
              <textarea name="message" class="frm" rows="6" placeholder="Mesaj..."></textarea><input type="text" name="city" value="" class="hide">

            </div>

<div class="pt-12 small"><i class="fas fa-lock fa-fw green"></i> Protecția datelor <small>(GDPR) (EU) 2016/679 <a href="https://en.wikipedia.org/wiki/General_Data_Protection_Regulation"><i class="fas fa-external-link-alt fa-fw"></i></a></small></div>

            <div class="pt-12">
              <button type="submit" class="frm frb dsblb"><i class="fas fa-paper-plane fa-fw"></i> Trimite</button>
            </div></form>
</form>

</div> <!-- ./hide-contact -->
          


</div>
<!-- ./form-ROW -->

<?php

// v1.0 090318

if(isset($_POST['city']) && !empty($_POST['city'])) {

echo "Hello Robot!";

exit;

}

if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message'])) {

echo "Hello Robot 2!";

exit;

}

$today = date("d/m/Y - G:i ");

/////////////////////
///////////
/////////
///////
/////
//



include_once("_connect.php");

// _POST Vars...

$name     		= htmlentities($_POST['name']);
$email    		= htmlentities($_POST['email']);
$phone    		= htmlentities($_POST['phone']);

$message1  		= htmlentities($_POST['message']);

$data 			= time(); 

$sql = "INSERT INTO table_name
(name, email, phone, message, data)
VALUES 
('$name', '$email', '$phone', '$message1', '$data')";





if ($conn->query($sql) === TRUE) {

//////

	//////



	///

// yeyy! Mail to owner...





$to_owner = "me@example.com";
$subject_owner = "New message from...";

$message_owner = "
<html>
<head>
<title>New message</title>
</head>
<body>
<p><h3>Mesaj nou pe site...</h3></p>
<p>Detalii mesaj:</p>
<ul>
<li>Name: $name</li>
<li>Phone: <a href=\"tel:$phone\">$phone</a></li>
<li>Email: $email</li>
<li>Data: $today</li>
<li>Message: $message1</li>
</ul>
</body>
</html>
";

// Always set content-type when sending HTML email
$headers_owner = "MIME-Version: 1.0" . "\r\n";
$headers_owner .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// More headers
$headers_owner .= 'From: Name<contact@example>' . "\r\n" . "Reply-to: $email" . "\r\n";
$headers_owner .= 'Cc: carbon-copy@example.com' . "\r\n";

mail($to_owner, $subject_owner, $message_owner, $headers_owner);







/////////////////
/// +++++++++++++++++++++ /////









exit;

} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();

?>

jQuery + CSS – Activate DIV background colour and deactivate other DIV’s bg colour

This little code delivers all the magic, if you are into one page websites/apps like me, this short code will simply save you lots of time.
This code simply activates(changes the style) of an DIV that is clicked on and removes the same style applied to other DIV(active button) in case it has another active style applied to another DIV.
It can be combined with a little CSS code to display a beautiful color transition.
You can see the code running on this little jsFiddle I made: https://jsfiddle.net/cosminr/ampjtwjp/

$(document).ready(function() {

	$('body').on('click', '.section-white', function() {
    	$('.section-white').removeClass('on-sel');
      	$(this).addClass('on-sel');
	});

});
.on-sel{    
	background-color: #82E0AA;
    -webkit-transition: background-color 1000ms linear;
    -ms-transition: background-color 1000ms linear;
    transition: background-color 1000ms linear;
}

How to Optimize Your Website And Obtain a Google Page Speed of 98-100?

First, please backup your files before you start modifying anything I write in this post.

Thank You!

First, why you should follow my advice? Well, almost anyone can tell you that a fast website is a good website and a good website is a mobile and desktop 100% compatible website but, as a developer, you need to test your site with Google’s Page Speed tool(https://developers.goo…).

Obtaining a good grade there can help your search engine traffic… So, what Google Page Speed score your project gets?

I’ve done a few projects with 98-99 out of 100, and a few with perfect 100.

I will list here a few “secrets” I used to boost my grade from 68/100 to 99/100.

1. Use only inline CSS

You need to use only inline css, period. Don’t link to any external frameworks(Bootstrap, etc.), don’t link to any Google Fonts file, to any particular style…

If you want to be productive, you ca use PHP to include_once(“”); your css files into the interpreted file.

If you want to use fontawesome or Google Fonts, you can put fontawesome file before you close your </body> tag.

You can also modify the Google Fonts .css file and include it inline into your source via PHP. Also, you can remove all the Vietnamese or Greek fonts from the Google Fonts file and use only the Latin style, works with english projects and most of the languages.

2. Insert the .js files at the end of the file

This is no secret that, inserting the .js files before you close </body> tag can get you a good Page Speed grade.

3. Use Server Side compression(gzip)

This is a pretty easy step, I provided instructions here on another post on how to do that.

4. Optimize images

Don’t exaggerate with images, use a low resolution image thumbnail, I use only < 10kb images. Specify the width and height of the image. You can use a free online tool to reduce the size of the images.

5. Minify css, js and html

This step gives anyone a lot of work if you are updating your site constantly… You can use free online tools to minify your css, html and js code.

6. Reduce the Server Response Time

Don’t load your server with requests, use, as much as you can only static content or make Ajax requests to content.

Bonus Point!

Transform your favicon in BASE64 text and include the code via PHP and get rid of a few connections that can slow down your website… I use this tool to convert my favicons: https://xaviesteve.co…

 

Hope this experience helps, try and play with this list and tell me your result.

Take a look at a sample page that I’ve recently made and got a great score: https://developers.google.com…

Best responsive CSS framework so far

There are a lot of CSS frameworks that use a grid system to display content on mobile and desktop(eg.: Bootstrap, Foundation…) but why load a lot of styles that you don’t need on your project? For example a series of form styles when you only need a simple Material Design form?

Lately I discovered Simple Grid, a simple, minimalistic responsive css framework that delivers only the basic functions of the grid.

You can take a look here: http://simplegrid.io/