S
S
sporium2017-09-29 20:50:52
JavaScript
sporium, 2017-09-29 20:50:52

How to save the inscription in cookies?

There is such a code, it is necessary that the inscription (the one that changes by clicking on the image) is saved in a cookie and remains when the page is reopened. How to do it? According to the TK, it is cookies and not localStorage.
I know that the curve code) just started teaching Js.

<!DOCTYPE HTML>
<html>

<head>



  <meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <!-- <link rel="stylesheet" href="lab1.css"> -->
</head>

<body>
 
  <script>


 
 
 
  document.onmousedown = function(e) {

  var dragElement = e.target;

  if (!dragElement.classList.contains('draggable')) return;

  var coords, shiftX, shiftY;

  startDrag(e.clientX, e.clientY);
  
  
  document.onmousemove = function(e) {
    moveAt(e.clientX, e.clientY);
  };

  dragElement.onmouseup = function() {
    
     // dragElement.onmouseup = function() {   мышка вверх
       
    finishDrag();
  };


  // -------------------------

  function startDrag(clientX, clientY) {

    shiftX = clientX - dragElement.getBoundingClientRect().left;
    shiftY = clientY - dragElement.getBoundingClientRect().top;

    dragElement.style.position = 'fixed';

    document.body.appendChild(dragElement);

    moveAt(clientX, clientY);
  };

  function finishDrag() {
     // конец переноса, перейти от fixed к absolute-координатам
    dragElement.style.top = parseInt(dragElement.style.top) + pageYOffset + 'px';
    dragElement.style.position = 'absolute';

    document.onmousemove = null;
    dragElement.onmouseup = null;
  }

  function moveAt(clientX, clientY) {
    // новые координаты
    var newX = clientX - shiftX;
    var newY = clientY - shiftY;

     // ------- обработаем вынос за нижнюю границу окна ------
  // новая нижняя граница элемента
    var newBottom = newY + dragElement.offsetHeight;

    // если новая нижняя граница вылезает вовне окна - проскроллим его
    if (newBottom > document.documentElement.clientHeight) {
      // координата нижней границы документа относительно окна
      var docBottom = document.documentElement.getBoundingClientRect().bottom;
  // scrollBy, если его не ограничить - может заскроллить за текущую границу документа
    // обычно скроллим на 10px
    // но если расстояние от newBottom до docBottom меньше, то меньше
   var scrollY = Math.min(docBottom - newBottom, 10);

     // ошибки округления при полностью прокрученной странице
    // могут привести к отрицательному scrollY, что будет означать прокрутку вверх
    // поправим эту ошибку
  if (scrollY < 0) scrollY = 0;

      window.scrollBy(0, scrollY);

      // резким движением мыши элемент можно сдвинуть сильно вниз
    // если он вышел за нижнюю границу документа -
    // передвигаем на максимально возможную нижнюю позицию внутри документа
    newY = Math.min(newY, document.documentElement.clientHeight - dragElement.offsetHeight);
    }


     // ------- обработаем вынос за верхнюю границу окна ------
   if (newY < 0) {
    // проскроллим вверх на 10px, либо меньше, если мы и так в самом верху
       var scrollY = Math.min(-newY, 10);
      if (scrollY < 0) scrollY = 0; // поправим ошибку округления

      window.scrollBy(0, -scrollY);
      // при резком движении мыши элемент мог "вылететь" сильно вверх, поправим его
    newY = Math.max(newY, 0);
    }


    // зажать в границах экрана по горизонтали
  // здесь прокрутки нет, всё просто
   if (newX < 0) newX = 0;
    if (newX > document.documentElement.clientWidth - dragElement.offsetHeight) {
      newX = document.documentElement.clientWidth - dragElement.offsetHeight;
    }

    dragElement.style.left = newX + 'px';
    dragElement.style.top = newY + 'px';
  }

 // отменим действие по умолчанию на mousedown (выделение текста, оно лишнее)
 return false;
}

  </script>
  <!-- <div onclick="MyFunc()" onclick="alert('аывафы')">asdasd</div> -->
<script>

 function getCookie(name) {
  var matches = document.cookie.match(new RegExp(
    "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
  ));
  return matches ? decodeURIComponent(matches[1]) : undefined;
}
 
 function setCookie(c_name, value, exdays) {
    var exdate.getElementById('boldStuff2');
</script>
 <script type="text/javascript">
function changeText1(){
 
 document.getElementById('boldStuff2').innerHTML = 'Img1';
}
function changeText2(){
  document.getElementById('boldStuff2').innerHTML = 'Img2';
}
function changeText3(){
 
 document.getElementById('boldStuff2').innerHTML = 'Img3';
}


</script>

<p>
Перемещалось изображение <b id='boldStuff2'>Ничего не перемещалось</b> </p>

 
 
  <div id="im1"  value=' 1 '  >
  

<img  src="1.jpg" width="200" class="draggable"  value=' 1 ' onmousedown='changeText1()' >
  
</div>  
    <div id="im2">
<img src="2.jpg" width="200" class="draggable" onmousedown='changeText2()'>
  
</div> 
    <div id="im3">
<img src="3.jpg" width="200" class="draggable"  onmousedown='changeText3()'>
  
</div>


<!-- function changeText3(){ -->
<!-- var userInput = document.getElementById('userInput').value;  -->
 <!-- document.getElementById('boldStuff2').innerHTML = 'Img3'; -->
<!-- } -->



</body>

</html>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oleg, 2017-09-29
@sporium

Where do you look for such customers who do not care what to pay for?
Read how to set a cookie, faith does not allow? https://learn.javascript.ru/cookies
document.cookie = "myText= твоя_надпись";

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question