Code Beispiele

Code Beispiele

Kleine Beispiele zur allgemeinen Anwendung.
Ob jQuery, PHP oder CSS, wir zeigen hier einige Tricks zur Anwendung.

CSS

Center Image - zentriert Image exkt in der Mitte
.image {
  display: flex;
  align-items: center;
  img {
    width: auto;
    margin: 0 auto;
    justify-items: center;
  }
}
Form Radio / Checkbox - Radio / Checkbox selbst stylen
input[type=radio],
    input[type=checkbox] {
      visibility: hidden;
      position: absolute;
    }

    input[type=radio] + label:before,
    input[type=checkbox] + label:before {
      height: 12px;
      width: 12px;
      margin-right: 10px;
      content: " ";
      display: inline-block;
      vertical-align: baseline;
      border: 1px solid $black;
    }

    input[type=radio] + label:before {
      border-radius: 50%;
    }

 input[type=checkbox] + label:before {
      border-radius: 2px;
    }

    input[type=radio]:checked + label:before,
    input[type=checkbox]:checked + label:before {
      background: $red;
    }
List with points - eigene Listpunkte
ul:not(.slick-dots) {
    background: $white;
    color: $black;
    list-style: none;
    padding-left: 20px;
    padding-right: 15px;
    border-radius: 5px;
    margin: 0;
    li {
      padding: 5px 0;
      @include media-breakpoint-up(md) {
        padding: 5px 0;
      }
      &:before {
        content: "\2022";
        position: absolute;
        left: 15px;
        font-size: 20px;
        display: inline-block;
        color: $black;
      }
    }
  }

jQuery

Random - Ordnet die ul/li Elemente nach Zufall neu an.
var max = $('#myParent li.item').length;
$('#myParent').children('li.item').sort(function(){
return Math.random()*max > (max/2) ? 1 : -1;
}).each(function(){
$(this).appendTo($(this).parent());
});
PageScroll - Scrollt zur ID der Page und setzt das menu aktiv
$('.submenu li a').on('click', function(e) {
        e.preventDefault();
        var activeItem = $(this);
        var canvas = $(this).attr('href');
        $('.submenu li a.active').removeClass('active');
        $('html, body').animate({
            scrollTop: $(canvas).offset().top - 110 + 'px'
        }, 2000, function() {
            $('.submenu li a.active').removeClass('active');
            activeItem.addClass('active');
        })
    });
SortDiv - sotiert DIV bei resize neu an
$(document).ready(function() {
	$(window).on("load resize",function(e){
	    var xwindow=$(document).width();
		if(xwindow >= 1540) {
			sortmy($('.container'),"l");
	    } else if(xwindow > 640 && xwindow < 1540){
	    	sortmy($('.container'),"m");
		} else if(xwindow <= 640){
			sortmy($('.container'),"s");
		}
    });
 });

 function sortmy(container,device){
	   $container = container;
	   if(device == 'l'){
			$fields = $("div[data-lsort]", $container);
	   } else if(device == 'm'){
		   $fields = $("div[data-msort]", $container);
	   } else {
		   $fields = $("div[data-ssort]", $container);
	   }
	   sorted = [];
	   $fields.detach().each(function() {
		   if(device == 'l'){
				sorted[parseInt(this.getAttribute("data-lsort"), 10)] = this;
		   } else if(device == 'm'){
			   sorted[parseInt(this.getAttribute("data-msort"), 10)] = this;
		   } else {
			   sorted[parseInt(this.getAttribute("data-ssort"), 10)] = this;
		   }
	   });
	   for (index in sorted) {
	       if (String(Number(index)) === index) {
	           $container.append(sorted[index]);
	       }
	   }
}
ExitPage - beim verlassen der Seite
$(document).ready(function() {
	  $(document).mousemove(function(e) {
		$('#exitpopup').css('left', (window.innerWidth/2 - $('#exitpopup').width()/2));
		$('#exitpopup').css('top', (window.innerHeight/2 - $('#exitpopup').height()/2));
                var screenTop = $(document).scrollTop();
		 if(e.pageY <= (screenTop + 5))
		{
		  // Show the exit popup
		  $('#exitpopup_bg').fadeIn();
		  $('#exitpopup').fadeIn();
		}
	  });
	  $('#exitpopup_bg').click(function(){
		$('#exitpopup_bg').fadeOut();
		$('#exitpopup').slideUp();
	  });
});
Make fieldset collapse - Dropdown Fieldset
$(window).on('load resize', function() {
        var screen = $(window).width();
        if(screen < 992) {
          auswahl = 1
          $('fieldset').each(function() {
            $('#auswahl' + auswahl).addClass('collapse').removeClass('show');
            $(this).find('legend').on('click touch',function() {
              $(this).toggleClass('isOpen');
              $('#auswahl' + auswahl).collapse('toggle');
            });
            auswahl++;
          });
        } else {
          auswahl = 1
          $('fieldset').each(function() {
            $('#auswahl' + auswahl).removeClass('collapse').removeClass('show');
            auswahl++;
          });
        }
      });
InfiniteShow - show more on click
CSS first n selectors
.product-finder .views-row:nth-child(n+13) {
  display: none;
}

// product filter
// first: clean doubles
  var found = {};
  $('.views-field-nid').each(function(){
    var $ids = $(this).find('.field-content').text();
    //console.log($ids);
    if (found[$ids] == null)
      found[$ids] = true;
    else
      $(this).closest('.views-row').remove();
  });
// set button for more
  var but = '<ul class="js-pager__items pager" data-drupal-views-infinite-scroll-pager="">\n' +
    '  <li class="pager__item">\n' +
    '    <span class="button more" href="?kat=All&amp;kat2=All&amp;eig=All&amp;ges=All&amp;lab=All&amp;s=&amp;page=1" title="Weitere Produkte anzeigen" rel="next">Mehr anzeigen</span>\n' +
    '  </li>\n' +
    '</ul>';
  var anz = $(".product-finder .views-row").length;
  if(anz > 13) {
    $('.product-finder').append(but);
  }
// infinite show
  $('.more').click(function () {
    $('.product-finder .views-row:hidden').slice(0, 12).show();
    if ($('.product-finder .views-row').length == $('.product-finder .views-row:visible').length) {
      $('.more').hide();
    }
  });

PHP

DOM - DOMDocument::getElementById
function HomepageLaden($url, $postdata)
		{
		$agent = "Meine Browserkennung v1.0 :)";
		$header[] = "Accept: text/vnd.wap.wml,*.*";
		$ch = curl_init($url);

		if ($ch)
			{
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($ch,    CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch,    CURLOPT_USERAGENT, $agent);
			curl_setopt($ch,    CURLOPT_HTTPHEADER, $header);
			curl_setopt($ch,    CURLOPT_FOLLOWLOCATION, 1);


			if (isset($postdata))
				{
				curl_setopt($ch,    CURLOPT_POST, 1);
				curl_setopt($ch,    CURLOPT_POSTFIELDS, $postdata);
				}

			$tmp = curl_exec ($ch);
			curl_close ($ch);
			}
		return $tmp;
	}
	$_url = "http://domain.tld/site.html";
	$_buffer = HomepageLaden($_url, "");

	$dom = new DOMDocument();
	$dom->loadHTML($_buffer);

	// Adresse
	$divNode = $dom->getElementById('profil_name_adresse');
        echo $divNode->childNodes;
DOM - DOMDocument::getElementByClassName
$dom = new DOMDocument();
$dom->loadHTMLFile('http://www.domain.com/search?q=schlauchwagen');
	$classname = 'product-item';
	$finder = new DomXPath($dom);
	$nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");
	$tmp_dom = new DOMDocument();
	$i=0;
	foreach ($nodes as $node)
	{
		if($i<=5)
		{
			echo $i;
			$tmp_dom->appendChild($tmp_dom->importNode($node,true));
			$i++;
		}

    }
	$innerHTML.=trim($tmp_dom->saveHTML());
	echo $innerHTML;
Register Globals - wenn register_globals ausgeschaltet ist
if (!ini_get('register_globals')) {
    foreach($_REQUEST as $key => $value) {
	   $GLOBALS[$key] = $value;
	}
}
Passwort - decrypt und encrypt Passwort
$input = "SmackFactory";

$encrypted = encryptIt( $input );
$decrypted = decryptIt( $encrypted );

echo $encrypted . '<br />' . $decrypted;

function encryptIt( $q ) {
    $cryptKey  = 'qJB0rGtIn5UB1xG03efyCp';
    $qEncoded      = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), $q, MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ) );
    return( $qEncoded );
}

function decryptIt( $q ) {
    $cryptKey  = 'qJB0rGtIn5UB1xG03efyCp';
    $qDecoded      = rtrim( mcrypt_decrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), base64_decode( $q ), MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ), "\0");
    return( $qDecoded );
}

SQL

ID problem - das bekannte ID Problem
DELETE FROM field_downloads_files WHERE field_downloads_files_target_id = xx;
DELETE FROM revision__field_downloads_files WHERE field_downloads_files_target_id = xx;

Dies löst das ID Problem

HTACCESS

Hidde Files - bestimmte Files schützen
<FilesMatch "\.(pdf)$">
  Order Allow,Deny
  Deny from all
</FilesMatch>
Verlinkung - Fehlerfrei Verlinkung
RewriteEngine On
# ˆ
Redirect 301 / http://www.xn--agentur-verkaufsfrderung-1oc.de
# ‰
Redirect 301 / http://www.xn--bettwsche-versand-uqb.ch
Schutz - allgemeiner Zugriffsschutz
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?developer.uidev\.de/archiv/referenzen/cheatsheets/ [NC,OR]
RewriteCond %{HTTP_REFERER} !^http://(www\.)?developer.uidev\.de/archiv/layouts/responsive-html/ [NC]
RewriteRule \.(gif|jpe?g|png|pdf|zip)$ - [F]
Subdomain - Weiterleitung bei Subdomains
RewriteCond %{HTTP_HOST} !^(mini|alpina|bmw|gebraucht|www)\.xxii\.de$
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
www/https - Weiterleitung auf www
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
#if its SSL
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]